OpenCV Python图像旋转,0-360度随机旋转,同时去除黑边

import cv2 as cv
import numpy as np
import os
from math import *
import random
import numpy as np

x= random.randint(0, 360)
degree=x
height,width = img.shape[:2]

M = cv.getRotationMatrix2D((width/2,height/2),degree,1)
heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))
widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))

M[0, 2] += (widthNew - width) / 2  
M[1, 2] += (heightNew - height) / 2  

im_rotate = cv.warpAffine(img,M,(widthNew,heightNew), borderValue=(255, 255, 255))
im_rotate = cv.resize(im_rotate,(320,320))
cv.imshow("test",im_rotate)
cv.imwrite("test_new4.jpg",im_rotate)
cv.waitKey()   
cv.destroyAllWindows()

在下面一行中也可以指定旋转角度,从而固定旋转角度

x= random.randint(0, 360)

去除黑边主要依靠这部分代码

degree=x
height,width = img.shape[:2]

M = cv.getRotationMatrix2D((width/2,height/2),degree,1)
heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))
widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))

M[0, 2] += (widthNew - width) / 2  
M[1, 2] += (heightNew - height) / 2  

im_rotate = cv.warpAffine(img,M,(widthNew,heightNew), borderValue=(255, 255, 255))

设置x = -233 效果如下:

OpenCV Python图像旋转,0-360度随机旋转,同时去除黑边_第1张图片

你可能感兴趣的:(OpenCV,计算机视觉,opencv,python)