如何使用 OpenCV 进行图像旋转?
我给你**最简单、最实用、不会裁图**的 OpenCV 图像旋转方法,**Python 直接复制运行**! # OpenCV 图像旋转(3 行核心代码) ## 1. 最常用:任意角度旋转(自动居中 + 不裁图) ```python import cv2 import numpy as np # 1. 读取图片 img = cv2.imread("test.jpg") h, w = img.shape[:2] # 获取高、宽 # 2. 旋转角度(正数=逆时针,负数=顺时针) angle = 45 # 3. 计算旋转中心 + 旋转矩阵 center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) # 1.0=缩放比例 # 4. 执行旋转(最关键) rotated = cv2.warpAffine(img, M, (w, h)) # 5. 显示 cv2.imshow("旋转后", rotated) cv2.waitKey(0) ``` --- # 2. 解决旋转后**被裁剪**的问题(必看) 普通旋转会把图片边角切掉,用下面代码**完整显示**: ```python def rotate_image(img, angle): h, w = img.shape[:2] center = (w//2, h//2) M = cv2.getRotationMatrix2D(center, angle, 1.0) # 计算新的宽高,防止裁剪 cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) new_w = int(h * sin + w * cos) new_h = int(h * cos + w * sin) M[0, 2] += (new_w / 2) - center[0] M[1, 2] += (new_h / 2) - center[1] return cv2.warpAffine(img, M, (new_w, new_h)) # 使用 rotated = rotate_image(img, 45) ``` --- # 3. 快速旋转 90°/180°/270°(更简单) ```python # 逆时针90度 rot90 = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) # 顺时针90度 rot90 = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) # 180度 rot180 = cv2.rotate(img, cv2.ROTATE_180) ``` --- # 超简记忆口诀 ``` 获取中心 → getRotationMatrix2D → warpAffine





