Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不使用cv2.getRotationMatrix2D的情况下手动旋转图像_Python_Opencv - Fatal编程技术网

Python 如何在不使用cv2.getRotationMatrix2D的情况下手动旋转图像

Python 如何在不使用cv2.getRotationMatrix2D的情况下手动旋转图像,python,opencv,Python,Opencv,我想在不使用内置cv2库的情况下旋转图像。我看到了这个等式 但我不知道如何在代码中应用它 //编辑只需使用PIL中的图像库即可。这是另一个图像处理库。示例如下所示,更多信息请访问: 只需使用PIL中的图像库。这是另一个图像处理库。示例如下所示,更多信息请访问: 这个方程告诉你的是,如何匹配从初始图像到最终图像的坐标。 请注意,该方程式适用于围绕0的旋转 下面是C++代码,但是你可以翻译(ItP2是一个在4个相邻像素之间线性插值的函数,并且在原始图像的外时还返回另一个值): for(intx

我想在不使用内置cv2库的情况下旋转图像。我看到了这个等式

但我不知道如何在代码中应用它


//编辑

只需使用PIL中的图像库即可。这是另一个图像处理库。示例如下所示,更多信息请访问:


只需使用PIL中的图像库。这是另一个图像处理库。示例如下所示,更多信息请访问:


这个方程告诉你的是,如何匹配从初始图像到最终图像的坐标。 请注意,该方程式适用于围绕0的旋转

下面是C++代码,但是你可以翻译(ItP2是一个在4个相邻像素之间线性插值的函数,并且在原始图像的外时还返回另一个值):


for(intx=0;x这个等式告诉你的是,如何匹配从初始图像到最终图像的坐标。
请注意,该方程式适用于围绕0的旋转

下面是C++代码,但是你可以翻译(ItP2是一个在4个相邻像素之间线性插值的函数,并且在原始图像的外时还返回另一个值):


for(int x=0;x以下代码显示如何在不使用任何预定义功能或模块的情况下逆时针旋转图像90度,
cv2仅用于读取要旋转的图像,然后在应用逻辑后,显示最终旋转的图像
通过此代码,您可以旋转任何大小的图像

img = cv2.imread(ImageName,1)
shape=img.shape
rev=[]
rev.append(shape[1])
rev.append(shape[0])
revF=tuple(rev)
rotate=np.zeros(revF,dtype=object)


for i in range (len(img)):
    for j in range(len(img[i])):
             x=len(img[i])-1-j
             rotate[x][i]=img[i][j]

fi=[]
for i in range(len(rotate)):
    for j in range(len(rotate[i])):
       fi.append(rotate[i][j])
final=np.array(fi).reshape(revF[0],revF[1],3)
cv2.imshow("Image",final)
cv2.imwrite("ImageRotate90anti.jpg",(final))
cv2.waitKey(0)

以下代码显示如何在不使用任何预定义功能或模块的情况下逆时针旋转图像90度, cv2仅用于读取要旋转的图像,然后在应用逻辑后,显示最终旋转的图像 通过此代码,您可以旋转任何大小的图像

img = cv2.imread(ImageName,1)
shape=img.shape
rev=[]
rev.append(shape[1])
rev.append(shape[0])
revF=tuple(rev)
rotate=np.zeros(revF,dtype=object)


for i in range (len(img)):
    for j in range(len(img[i])):
             x=len(img[i])-1-j
             rotate[x][i]=img[i][j]

fi=[]
for i in range(len(rotate)):
    for j in range(len(rotate[i])):
       fi.append(rotate[i][j])
final=np.array(fi).reshape(revF[0],revF[1],3)
cv2.imshow("Image",final)
cv2.imwrite("ImageRotate90anti.jpg",(final))
cv2.waitKey(0)

这通常是通过迭代输出图像像素并找到它对应的输入图像像素,使用旋转矩阵进行反向旋转来完成的。下面代码的一些注释和改进:
1-使用偏移是因为我相对于中心位置旋转图像(想想用钢笔握住图像中心并旋转它),而不是从左上角旋转图像。
2-我创建了最大可能输出大小的图像,更好的方法是根据输入图像大小和旋转量计算必要的输出大小。
3-如代码中所述,与其匹配输入图像中的单个像素,不如在确定输出图像中像素的值时使用最近4个输入图像像素的线性插值

import numpy as np
import math
from scipy import ndimage
from PIL import Image


#  inputs
img = ndimage.imread("A.png")
rotation_amount_degree = 45

#  convert rotation amount to radian
rotation_amount_rad = rotation_amount_degree * np.pi / 180.0


#  get dimension info
height, width, num_channels = img.shape


#  create output image, for worst case size (45 degree)
max_len = int(math.sqrt(height*height + width*width))
rotated_image = np.zeros((max_len, max_len, num_channels))
#rotated_image = np.zeros((img.shape))


rotated_height, rotated_width, _ = rotated_image.shape
mid_row = int( (rotated_height+1)/2 )
mid_col = int( (rotated_width+1)/2 )

#  for each pixel in output image, find which pixel
#it corresponds to in the input image
for r in range(rotated_height):
    for c in range(rotated_width):
        #  apply rotation matrix, the other way
        y = (r-mid_col)*math.cos(rotation_amount_rad) + (c-mid_row)*math.sin(rotation_amount_rad)
        x = -(r-mid_col)*math.sin(rotation_amount_rad) + (c-mid_row)*math.cos(rotation_amount_rad)

        #  add offset
        y += mid_col
        x += mid_row

        #  get nearest index
        #a better way is linear interpolation
        x = round(x)
        y = round(y)

        #print(r, " ", c, " corresponds to-> " , y, " ", x)

        #  check if x/y corresponds to a valid pixel in input image
        if (x >= 0 and y >= 0 and x < width and y < height):
            rotated_image[r][c][:] = img[y][x][:]


#  save output image
output_image = Image.fromarray(rotated_image.astype("uint8"))
output_image.save("rotated_image.png")
将numpy导入为np
输入数学
从scipy导入ndimage
从PIL导入图像
#投入
img=ndimage.imread(“A.png”)
旋转量度=45
#将旋转量转换为弧度
旋转量弧度=旋转量弧度*np.pi/180.0
#获取维度信息
高度、宽度、通道数=img.shape
#创建输出图像,最坏情况下的大小(45度)
max_len=int(数学sqrt(高度*高度+宽度*宽度))
旋转的图像=np.0((最大长度、最大长度、数量通道))
#旋转的图像=np.零((图像形状))
旋转的高度、旋转的宽度、旋转的图像形状
中间行=整数((旋转高度+1)/2)
中柱=int((旋转宽度+1)/2)
#对于输出图像中的每个像素,找到哪个像素
#它对应于输入图像中的
对于范围内的r(旋转高度):
对于范围内的c(旋转宽度):
#应用旋转矩阵,另一种方法
y=(r-mid\u col)*数学cos(旋转量\u rad)+(c-mid\u行)*数学sin(旋转量\u rad)
x=-(r-mid\u col)*数学sin(旋转量\u rad)+(c-mid\u行)*数学cos(旋转量\u rad)
#添加偏移量
y+=中柱
x+=中排
#获取最近的索引
#更好的方法是线性插值
x=圆形(x)
y=圆形(y)
#打印(r,“,c,”,对应于->”,y,“,x)
#检查x/y是否对应于输入图像中的有效像素
如果(x>=0,y>=0,x<宽度,y<高度):
旋转的_图像[r][c][:]=img[y][x][:]
#保存输出图像
output\u image=image.fromarray(旋转的\u image.astype(“uint8”))
输出_image.save(“rotated_image.png”)


这通常是通过迭代输出图像像素并找到它对应的输入图像像素来完成的,使用旋转矩阵进行反向旋转。下面代码的一些注释和改进:
1-使用偏移是因为我相对于中心位置旋转图像(想想用钢笔握住图像中心并旋转它),而不是从左上角旋转图像。
2-我创建了最大可能输出大小的图像,更好的方法是根据输入图像大小和旋转量计算必要的输出大小。
3-如代码中所述,与其匹配输入图像中的单个像素,不如在确定输出图像中像素的值时使用最近4个输入图像像素的线性插值

import numpy as np
import math
from scipy import ndimage
from PIL import Image


#  inputs
img = ndimage.imread("A.png")
rotation_amount_degree = 45

#  convert rotation amount to radian
rotation_amount_rad = rotation_amount_degree * np.pi / 180.0


#  get dimension info
height, width, num_channels = img.shape


#  create output image, for worst case size (45 degree)
max_len = int(math.sqrt(height*height + width*width))
rotated_image = np.zeros((max_len, max_len, num_channels))
#rotated_image = np.zeros((img.shape))


rotated_height, rotated_width, _ = rotated_image.shape
mid_row = int( (rotated_height+1)/2 )
mid_col = int( (rotated_width+1)/2 )

#  for each pixel in output image, find which pixel
#it corresponds to in the input image
for r in range(rotated_height):
    for c in range(rotated_width):
        #  apply rotation matrix, the other way
        y = (r-mid_col)*math.cos(rotation_amount_rad) + (c-mid_row)*math.sin(rotation_amount_rad)
        x = -(r-mid_col)*math.sin(rotation_amount_rad) + (c-mid_row)*math.cos(rotation_amount_rad)

        #  add offset
        y += mid_col
        x += mid_row

        #  get nearest index
        #a better way is linear interpolation
        x = round(x)
        y = round(y)

        #print(r, " ", c, " corresponds to-> " , y, " ", x)

        #  check if x/y corresponds to a valid pixel in input image
        if (x >= 0 and y >= 0 and x < width and y < height):
            rotated_image[r][c][:] = img[y][x][:]


#  save output image
output_image = Image.fromarray(rotated_image.astype("uint8"))
output_image.save("rotated_image.png")
将numpy导入为np
输入数学
从scipy导入ndimage
从PIL导入图像
#投入
img=ndimage.imread(“A.png”)
旋转量度=45
#将旋转量转换为弧度
旋转量弧度=旋转量弧度*np.pi/180.0
#获取维度信息
高度、宽度、通道数=img.shape
#创建输出图像,最坏情况下的大小(45度)
max_len=int(数学sqrt(高度*高度+宽度*宽度))
旋转的图像=np.0((最大长度、最大长度、数量通道))
#旋转的图像=np.零((图像形状))
旋转的高度、旋转的宽度、旋转的图像形状
中间行=整数((旋转高度+1)/2)
中柱=int((旋转宽度+1)/2)
#对于输出图像中的每个像素,找到哪个像素
#它对应于输入图像中的
对于范围内的r(旋转高度):
对于范围内的c(旋转宽度):
#应用旋转矩阵,另一种方法
y=(r-mid\u col)*数学cos(旋转量\u rad)+(c
def rotate_image(img, degrees, output_scale="crop"):

    # openCV solution:
    # x, y = image.shape
    # rot_mat = cv2.getRotationMatrix2D((x // 2, y // 2), angle, 1.0)
    # result = cv2.warpAffine(image, rot_mat, image.shape, flags=cv2.INTER_LINEAR)

    assert output_scale in ["crop", "full"], "output_scale should be either 'crop' or 'full'"
    #  convert rotation amount to radian
    rot_rad = degrees * np.pi / 180.0
    rotate_m = np.array([[np.cos(rot_rad), np.sin(rot_rad)],
                         [- np.sin(rot_rad), np.cos(rot_rad)]])

    # If output_scale = "full", the image must be inserted into a bigger frame, so the coordinates would be translated
    # appropriately.
    gray_scale = False
    if len(img.shape) < 3:
        img = img.reshape(*img.shape, 1)
        gray_scale = True

    h, w, c = img.shape
    if output_scale == "full":
        diagonal = int(np.sqrt(h * h + w * w))   # Pytagoras theorm - the diagonal is the longest line in the rectangle
        im_padded = np.zeros((diagonal, diagonal, c))
        center_h = int((diagonal - h) // 2)
        center_w = int((diagonal - w) // 2)
        im_padded[center_h:-center_h, center_w:-center_w, :] = img
        img = im_padded
        rotated_image = np.zeros((diagonal, diagonal, c))
        h, w, c = img.shape
    else:
        rotated_image = np.zeros((h, w, c))

    # Rotate and shift the indices, from PICTURE to SOURCE (and NOT the intuitive way)
    indices_org = np.array(np.meshgrid(np.arange(h), np.arange(w))).reshape(2, -1)
    indices_new = indices_org.copy()
    indices_new = np.dot(rotate_m, indices_new).astype(int)   # Apply the affineWrap
    mu1 = np.mean(indices_new, axis=1).astype(int).reshape((-1, 1))
    mu2 = np.mean(indices_org, axis=1).astype(int).reshape((-1, 1))
    indices_new += (mu2-mu1)   # Shift the image back to the center

    # Remove the pixels in the rotated image, that are now out of the bounds of the result image
    # (Note that the result image is a rectangle of shape (h,w,c) that the rotated image is inserted into, so in the
    # case of a "full" output_scale, these are just black pixels from the padded image...).
    t0, t1 = indices_new
    t0 = (0 <= t0) & (t0 < h)
    t1 = (0 <= t1) & (t1 < w)
    valid = t0 & t1
    indices_new = indices_new.T[valid].T
    indices_org = indices_org.T[valid].T

    #
    xind, yind = indices_new
    xi, yi = indices_org
    rotated_image[xi, yi, :] = img[xind, yind, :]

    if gray_scale:
        rotated_image = rotated_image.reshape((h, w))

    return rotated_image.astype(np.uint8)