Tôi đang cố gắng xoay một hình ảnh một số độ rồi hiển thị nó trong cửa sổ. ý tưởng của tôi là để xoay và sau đó hiển thị nó trong một cửa sổ mới với chiều rộng mới và chiều cao của cửa sổ được tính từ chiều rộng cũ và height:Python 2.7.3 + OpenCV 2.4 sau khi cửa sổ xoay không vừa với Hình ảnh
new_width = x * cos angle + y * sin angle
new_height = y * cos angle + x * sin angle
Tôi đã chờ đợi kết quả để trông giống như dưới đây:
nhưng nó quay ra kết quả như sau:
và mã của tôi là ở đây:
#!/usr/bin/env python -tt
#coding:utf-8
import sys
import math
import cv2
import numpy as np
def rotateImage(image, angel):#parameter angel 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(angel)
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,angel,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)
Phải có một số sai lầm ngu ngốc trong mã dẫn của tôi cho vấn đề này, nhưng tôi không thể hình dung nó ra ... và tôi biết mã của tôi là không đủ pythonic :(.. xin lỗi vì điều đó ..
Có ai có thể giúp tôi không?
nhất,
bearzk
Cảm ơn câu trả lời ngắn gọn và mã được chú thích. Giải quyết vấn đề một cách độc đáo. – leomelzer