想象一下,我有这些图片:
我希望左边的图像像中间的图像一样旋转,而不是正确的图像。我如何使用Python和OpenCV来做到这一点。我查看了getRotationMatrix2D
和warpAffine
,但有关它的示例会将我的图像转换为正确的图像。
答案 0 :(得分:9)
这是迄今为止我发现的旋转图像同时避免裁剪图像的最佳解决方案。
Rotate an image without cropping in OpenCV in C++
one.innerHTML += "Today is : " + days[d.getDay()] + "\n";
one.innerHTML += " Current time is : " + d.getHours() + " : " + d.getMinutes() + " : " + d.getSeconds();
当角度为90 * n时,您可以添加检查以避免某些计算,但此功能将适用于任何角度。
答案 1 :(得分:5)
由于我不知道您的代码,我仍然会猜测使用imutils.rotate_bound
函数可以解决问题。例如:rotate = imutils.rotate_bound(image, angle)
答案 2 :(得分:4)
如果您仅关心numpy的90度旋转。这要容易得多,并且可以在opencv输入上使用:
import numpy as np
rotated_image = np.rot90(im)
答案 3 :(得分:0)
您也可以使用填充,即在图像的两侧添加边框,然后旋转它以避免从原始图像中裁剪。
def rotate_im(image, angle)
image_height = image.shape[0]
image_width = image.shape[1]
diagonal_square = (image_width*image_width) + (
image_height* image_height
)
#
diagonal = round(sqrt(diagonal_square))
padding_top = round((diagonal-image_height) / 2)
padding_bottom = round((diagonal-image_height) / 2)
padding_right = round((diagonal-image_width) / 2)
padding_left = round((diagonal-image_width) / 2)
padded_image = cv2.copyMakeBorder(image,
top=padding_top,
bottom=padding_bottom,
left=padding_left,
right=padding_right,
borderType=cv2.BORDER_CONSTANT,
value=0
)
padded_height = padded_image.shape[0]
padded_width = padded_image.shape[1]
transform_matrix = cv2.getRotationMatrix2D(
(padded_height/2,
padded_width/2), # center
angle, # angle
1.0) # scale
rotated_image = cv2.warpAffine(padded_image,
transform_matrix,
(diagonal, diagonal),
flags=cv2.INTER_LANCZOS4)
return rotated_image
答案 4 :(得分:0)
这是通过使用cv2.rotate(frame,rotateCode = 1)旋转图像帧并通过使用帧的cv2.CAP_PROP_FRAME_WIDTH和cv2.CAP_PROP_FRAME_HEIGHT来缩放或调整大小的最简单方法。
import numpy as np
import cv2
cam = cv2.VideoCapture(2)
while(True):
# Capture frame-by-frame
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # You can change frame width by chaning number.
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # You can change frame height by chaning number.
ret, frame = cam.read()
new_frame=cv2.rotate(frame,rotateCode = 1)
# Display the resulting frame
cv2.imshow('frame',new_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cam.release()
cv2.destroyAllWindows()
希望它能对您有所帮助。
答案 5 :(得分:-1)
它的简单不需要任何warpaffine或任何计算检查此代码
import numpy as np
from PIL import ImageGrab
import cv2
angle = -90
scale = 1.0
while True:
img = ImageGrab.grab()
img_np = np.array(img)
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
new = cv2.rotate(frame,rotateCode = 0)# this is the line to rotate the image
true = cv2.resize(new, (0,0), fx = 0.6, fy = 0.6) # with fxand fy u can control the size
cv2.imshow('output', true)
if cv2.waitKey(1) == 27:
break
cv2.destroyAllWindows()