通常图像的旋转使用
cv2.getRotationMarix2D(获取变换矩阵)
cv2.warpAffine(进行仿射变换)
这两个API较多,但是变换过后往往会截断部分图像的内容
另外看到一种思路是创建一个全0数组去放置变换后的图片, 然后截去非图片部分, 如果是旋转90度这种特殊角度, 可以手动构建旋转矩阵matRotate ,以保证仿射 平移后的图片不会有缺失, 但经过测试, 这种方式还是存在风险, 因此仅提供一种思路, 代码如下:
def rotate(image, angle):
"""
:param image: 原图像
:param angle: 旋转角度
:return: 旋转后的图像
"""
height, width = image.shape[:2]
matRotate = cv.getRotationMatrix2D((height // 2, width // 2), angle, 1)
dst = cv.warpAffine(image, matRotate, (width * 2, height * 2))
rows, cols = dst.shape[:2]
for col in range(0, cols):
if dst[:, col].any():
left = col
break
for col in range(cols - 1, 0, -1):
if dst[:, col].any():
right = col
break
for row in range(0, rows):
if dst[row, :].any():
up = row
break
for row in range(rows - 1, 0, -1):
if dst[row, :].any():
down = row
break
res_widths = abs(right - left)
res_heights = abs(down - up)
res = np.zeros([res_heights, res_widths, 3], np.uint8)
for res_width in range(res_widths):
for res_height in range(res_heights):
res[res_height, res_width] = dst[up + res_height, left + res_width]
return res
最后是这样解决的: 仅旋转90 180 270三个角度的话, 通过转秩和翻折的方式就能够达到效果
def rotate(image, angle):
"""
:param image: 原图像
:param angle: 旋转角度
:return: 旋转后的图像
"""
if angle == 0:
return image
if angle == 90:
dst1 = cv.transpose(image)
dst2 = cv.flip(dst1, 0)
return dst2
if angle == 180:
dst1 = cv.flip(image, 1)
dst2 = cv.flip(dst1, 0)
return dst2
if angle == 270:
dst1 = cv.transpose(image)
dst2 = cv.flip(dst1, 1)
return dst2