当我们对图像进行旋转后,常常会导致边缘存在黑边,尤其当将该旋转后的图像“贴图”到其他图像上时,黑边的存在感极强,但是这并不是我们所需要的。
解决方案:
- 贴图采用PIL第三方库完成
- 若有坐标等信息,采用旋转矩阵进行转换(下方有转换代码)
def rotate(img, rotate_angle):
"""
img: Image读取图像
rotate_angle: 旋转角度
return: 旋转后的图像(无黑边),旋转矩阵
"""
(h, w) = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR).shape[:2]
(cx, cy) = (w / 2, h / 2)
rotate_angle = rotate_angle % 360
img = img.rotate(rotate_angle, Image.BICUBIC, expand=1)
# 设置旋转矩阵
M = cv2.getRotationMatrix2D((cx, cy), rotate_angle, 1)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# 计算图像旋转后的新边界
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
# 调整旋转矩阵的移动距离(以图像中心为旋转中心,画图可理解该步骤)
M[0, 2] += (nW / 2) - cx
M[1, 2] += (nH / 2) - cy
return img, M
将原图像对应坐标转换为旋转后的坐标,其中matrix即为返回的旋转矩阵,代码如下
# points: [(554, 523), (808, 523), (808, 543), (554, 543)]
points = np.array(points)
points = points.reshape(-1, 2)
n = np.shape(points)[0]
z = np.ones(n)
points = np.c_[points, z]
rotate_point = np.dot(matrix, np.transpose(points))
rotate_point = list(rotate_point.transpose().flatten().astype(int).reshape(-1, 2))