在利用RotatedRect()和warpAffine()对图像进行旋转时,会经常遇到虽然参数都设置正确,但是最终的旋转的图像,却是得不到预期的结果,这主要还是没有理解 RotatedRect中返回的角度angle的问题,有关 RotatedRect中返回的角度angle的详细介绍请查看本人的另一篇文章(https://blog.csdn.net/qq_39430765/article/details/99431709),下面就出现的问题进行详细的分析与解决。
首先我们看一段代码,主要是旋转一幅图像。
import cv2 import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False def Get_minAreaRect(image): ''' 获取图片旋转角度 :param image: :return: cv2.minAreaRect(coords) ''' plt.figure(1) plt.imshow(image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.bitwise_not(gray) _, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY ) coords = np.column_stack(np.where(thresh > 0)) return cv2.minAreaRect(coords) def Rotate_Bound(image, angle): ''' 调整图片角度 :param image: :param angle: :return: image ''' h, w = image.shape[:2] cx, cy = w // 2, h // 2 M = cv2.getRotationMatrix2D((cx, cy), -angle, 1.0) print(M) cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) nw = int(h * sin + w * cos) nh = int(h * cos + w * sin) nh = h # M[0, 2] += (nw / 2) - cx # M[1, 2] += (nh / 2) - cy roi = cv2.warpAffine(image, M, (nw, nh), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) plt.figure(3) plt.imshow(roi) plt.axis('off') return roi def test(): image_path = "E:\\test\\w.png" image = cv2.imread(image_path) angle = Get_minAreaRect(image)[-1] print("旋转角度为: {:.3f}".format(angle)) print(Get_minAreaRect(image)) if angle > -80.: rotated = Rotate_Bound(image, angle) plt.figure(2) plt.text(10, 30, "旋转角度为:{:.2f}".format(angle), size='x-large', color='black', bbox=dict(facecolor='w', alpha=0.5)) plt.imshow(rotated) plt.axis('off') plt.savefig("image1.png") if __name__ == '__main__': test() plt.show()
首先,加载一幅图像,这幅图像由cv2.minAreaRect()函数得到的角度是由短边(图像的宽)和X轴组成的,原图像和旋转最终得到图像,如图所示。
然后,加载另一幅图像,这幅图像由cv2.minAreaRect()函数得到的角度是由长边(图像的高)和X轴组成的,原图像和旋转最终得到图像,如图所示。
从结果可以看出问题所在,第二幅图像(即角度是由长边(图像的高)和X轴组成的)旋转之后的结果不是我们预想的结果,而第一幅图像(即角度是由短边(图像的宽)和X轴组成的)旋转之后的结果是我们预想得到的结果,造成两种的不同结果的原因在于绕旋转中心旋转的边不同,第一幅图像是将短边(图像的宽)绕旋转中心旋转,最后使短边(图像的宽)与Y轴平行,而第二幅图像是将长边(图像的高)绕旋转中心旋转,最后使长边(图像的高)与Y轴平行,从而导致图像的结果与预想的结果不同。
为了解决这一问题,我们必须在对图像进行旋转变换时,判断哪一条边是形成角度的边,这样我们在旋转变换时,就可以保证不会出现错误,从而得到我们想要的结果。