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

Getting a incorrect picture output when running my self-made rotation algorithm

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

我觉得可能和我的padding有关系,但可能还有其他错误

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)

编辑:

我认为放错位置的图像位置可能与缺少正确的原点有关,但是我似乎找不到解决该问题的有效方法。

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

更新:

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

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()

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