运行我自制的旋转算法时得到不正确的图片输出

2023-12-28

为了更好地理解图像处理的工作原理,我决定创建自己的图像旋转算法,而不是使用 cv2.rotate() 但是,我遇到了奇怪的图片裁剪和像素错位问题。

我认为这可能与我的填充有关,但也可能有其他错误

import cv2

import math

import numpy as np
# Load & Show original image
img = cv2.imread('Lena.png', 0)
cv2.imshow('Original', img)

# Variable declarations
h = img.shape[0]  # Also known as rows

w = img.shape[1]  # Also known as columns

cX = h / 2 #Image Center X

cY = w / 2 #Image Center Y

theta = math.radians(100) #Change to adjust rotation angle

imgArray = np.array((img))

imgArray = np.pad(imgArray,pad_width=((100,100),(100,100)),mode='constant',constant_values=0) 
  #Add padding in an attempt to prevent image cropping

# loop pixel by pixel in image
for x in range(h + 1):

 for y in range(w + 1):

  try:
   TX = int((x-cX)*math.cos(theta)+(y-cY)*math.sin(theta)+cX) #Rotation formula 

   TY = int(-(x-cX)*math.sin(theta)+(y-cY)*math.cos(theta)+cY) #Rotation formula

   imgArray[x,y] = img[TX,TY]

  except IndexError as error:

   print(error)

cv2.imshow('Rotated', imgArray)

cv2.waitKey(0)

Edit:

我认为错误的图像位置可能与缺乏适当的原点有关,但是我似乎无法找到解决该问题的有效解决方案。


虽然我没有深入研究该领域的数学部分,但根据给定的信息,我认为矩阵旋转公式应该是这样的:

UPDATE:

正如我所承诺的,我深入研究了该领域并找到了您可以看到的解决方案,如下所示。主要技巧是我也在循环中交换了源索引和目标索引,因此舍入并不意味着出现任何问题:

import cv2
import math
import numpy as np


# Load & Show original image
img = cv2.imread('/home/george/Downloads/lena.png', 0)
cv2.imshow('Original', img)


# Variable declarations
h = img.shape[0]  # Also known as rows
w = img.shape[1]  # Also known as columns

p = 120
h += 2 * p 
w += 2 * p

cX = h / 2 #Image Center X
cY = h / 2 #Image Center Y

theta = math.radians(45) #Change to adjust rotation angle

imgArray = np.zeros_like((img))  

#Add padding in an attempt to prevent image cropping
imgArray = np.pad(imgArray, pad_width=p, mode='constant', constant_values=0)   
img = np.pad(img, pad_width=p, mode='constant', constant_values=0)   

# loop pixel by pixel in image
for TX in range(h + 1):
    for TY in range(w + 1):
        try:
            x = int( +(TX - cX) * math.cos(theta) + (TY - cY) * math.sin(theta) + cX) #Rotation formula 
            y = int( -(TX - cX) * math.sin(theta) + (TY - cY) * math.cos(theta) + cY) #Rotation formula

            imgArray[TX, TY] = img[x, y]

        except IndexError as error:
           pass
#           print(error)

cv2.imshow('Rotated', imgArray)
cv2.waitKey(0)
exit()

Note:如果您想更深入地了解该领域,请参阅 usr2564301 评论。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

运行我自制的旋转算法时得到不正确的图片输出 的相关文章

随机推荐