旋转窗口后的Python 2.7.3 + OpenCV 2.4不适合Image

bea*_*rzk 13 python opencv python-2.7

我试图将图像旋转一定角度然后在窗口中显示.我的想法是旋转,然后在一个新的窗口中显示它,窗口的新宽度和高度从旧的宽度和高度计算:

new_width = x * cos angle + y * sin angle
new_height = y * cos angle + x * sin angle
Run Code Online (Sandbox Code Playgroud)

我期待结果如下所示:

在此输入图像描述

但事实证明结果如下:

在此输入图像描述

我的代码在这里:

#!/usr/bin/env python -tt
#coding:utf-8

import sys
import math
import cv2
import numpy as np 

def rotateImage(image, angle):#parameter angle in degrees

    if len(image.shape) > 2:#check colorspace
        shape = image.shape[:2]
    else:
        shape = image.shape
    image_center = tuple(np.array(shape)/2)#rotation center

    radians = math.radians(angle)

    x, y = im.shape
    print 'x =',x
    print 'y =',y
    new_x = math.ceil(math.cos(radians)*x + math.sin(radians)*y)
    new_y = math.ceil(math.sin(radians)*x + math.cos(radians)*y)
    new_x = int(new_x)
    new_y = int(new_y)
    rot_mat = cv2.getRotationMatrix2D(image_center,angle,1.0)
    print 'rot_mat =', rot_mat
    result = cv2.warpAffine(image, rot_mat, shape, flags=cv2.INTER_LINEAR)
    return result, new_x, new_y

def show_rotate(im, width, height):
#    width = width/2
#    height = height/2
#    win = cv2.cv.NamedWindow('ro_win',cv2.cv.CV_WINDOW_NORMAL)
#    cv2.cv.ResizeWindow('ro_win', width, height)
    win = cv2.namedWindow('ro_win')
    cv2.imshow('ro_win', im)
    if cv2.waitKey() == '\x1b':
        cv2.destroyWindow('ro_win')

if __name__ == '__main__':

    try:
        im = cv2.imread(sys.argv[1],0)
    except:
        print '\n', "Can't open image, OpenCV or file missing."
        sys.exit()

    rot, width, height = rotateImage(im, 30.0)
    print width, height
    show_rotate(rot, width, height)
Run Code Online (Sandbox Code Playgroud)

我的代码中肯定会有一些愚蠢的错误导致这个问题,但是我无法弄明白......而且我知道我的代码不够pythonic :( ...那就是......

谁能帮我?

最好,

bearzk

Luk*_*uke 12

正如BloodyD的回答所说,cv2.warpAffine不会自动居中转换后的图像.相反,它只是使用变换矩阵变换每个像素.(这可以将像素移动到笛卡尔空间中的任何位置,包括原始图像区域之外的任何位置.)然后,当您指定目标图像大小时,它会抓取该大小的区域,从(0,0)开始,即左上角原始框架.变换后的图像中不包含该区域的任何部分都将被截断.

这是旋转和缩放图像的Python代码,结果居中:

def rotateAndScale(img, scaleFactor = 0.5, degreesCCW = 30):
    (oldY,oldX) = img.shape #note: numpy uses (y,x) convention but most OpenCV functions use (x,y)
    M = cv2.getRotationMatrix2D(center=(oldX/2,oldY/2), angle=degreesCCW, scale=scaleFactor) #rotate about center of image.

    #choose a new image size.
    newX,newY = oldX*scaleFactor,oldY*scaleFactor
    #include this if you want to prevent corners being cut off
    r = np.deg2rad(degreesCCW)
    newX,newY = (abs(np.sin(r)*newY) + abs(np.cos(r)*newX),abs(np.sin(r)*newX) + abs(np.cos(r)*newY))

    #the warpAffine function call, below, basically works like this:
    # 1. apply the M transformation on each pixel of the original image
    # 2. save everything that falls within the upper-left "dsize" portion of the resulting image.

    #So I will find the translation that moves the result to the center of that region.
    (tx,ty) = ((newX-oldX)/2,(newY-oldY)/2)
    M[0,2] += tx #third column of matrix holds translation, which takes effect after rotation.
    M[1,2] += ty

    rotatedImg = cv2.warpAffine(img, M, dsize=(int(newX),int(newY)))
    return rotatedImg
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


bel*_*kev 5

当你得到这样的旋转矩阵时:

rot_mat = cv2.getRotationMatrix2D(image_center,angel,1.0)
Run Code Online (Sandbox Code Playgroud)

您的“比例”参数设置为 1.0,因此如果您使用它来将图像矩阵转换为相同大小的结果矩阵,则它必然会被剪裁。

您可以改为获得这样的旋转矩阵:

rot_mat = cv2.getRotationMatrix2D(image_center,angel,0.5)
Run Code Online (Sandbox Code Playgroud)

这将同时旋转和收缩,在边缘周围留出空间(您可以先将其放大,以便最终得到大图像)。

此外,您似乎混淆了图像大小的 numpy 和 OpenCV 约定。OpenCV 使用 (x, y) 作为图像大小和点坐标,而 numpy 使用 (y,x)。这可能就是您从纵向到横向纵横比的原因。

我倾向于像这样明确说明它:

imageHeight = image.shape[0]
imageWidth = image.shape[1]
pointcenter = (imageHeight/2, imageWidth/2)
Run Code Online (Sandbox Code Playgroud)

等等...

最终,这对我来说很好用:

def rotateImage(image, angel):#parameter angel in degrees
    height = image.shape[0]
    width = image.shape[1]
    height_big = height * 2
    width_big = width * 2
    image_big = cv2.resize(image, (width_big, height_big))
    image_center = (width_big/2, height_big/2)#rotation center
    rot_mat = cv2.getRotationMatrix2D(image_center,angel, 0.5)
    result = cv2.warpAffine(image_big, rot_mat, (width_big, height_big), flags=cv2.INTER_LINEAR)
    return result
Run Code Online (Sandbox Code Playgroud)

更新:

这是我执行的完整脚本。只是 cv2.imshow("winname", image) 和 cv2.waitkey() 没有参数来保持它打开:

import cv2

def rotateImage(image, angel):#parameter angel in degrees
    height = image.shape[0]
    width = image.shape[1]
    height_big = height * 2
    width_big = width * 2
    image_big = cv2.resize(image, (width_big, height_big))
    image_center = (width_big/2, height_big/2)#rotation center
    rot_mat = cv2.getRotationMatrix2D(image_center,angel, 0.5)
    result = cv2.warpAffine(image_big, rot_mat, (width_big, height_big), flags=cv2.INTER_LINEAR)
    return result

imageOriginal = cv2.imread("/Path/To/Image.jpg")
# this was an iPhone image that I wanted to resize to something manageable to view
# so I knew beforehand that this is an appropriate size
imageOriginal = cv2.resize(imageOriginal, (600,800))
imageRotated= rotateImage(imageOriginal, 45)

cv2.imshow("Rotated", imageRotated)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)

那里真的不多......if __name__ == '__main__':如果它是您正在处理的真正模块,那么您绝对正确使用。