Python实现:
src = cv.imread("D://Image/lena.jpg")
h, w, ch = src.shape
cv.imshow("input", src)
dst = np.zeros(src.shape, src.dtype)
for row in range(h):
for col in range(w):
b, g, r = src[row, col]
dst[row, w - col - 1] = [b, g, r]
cv.imshow("output", dst)
openCV实现:
# API
xs = cv.flip(src, -1)
cv.imshow("xs", xs)
顺时针旋转90度:
cv2.rotate(src, cv2.ROTATE_90_CLOCKWISE)
顺时针旋转180度:
cv2.rotate(src, cv2.ROTATE_180)
顺时针旋转270度:
cv2.rotate(src, cv2.ROTATE_90_COUNTERCLOCKWISE)
图像旋转原理:
void cv::warpAffine ( InputArray src,
OutputArray dst,
InputArray M,
Size dsize,
int flags = INTER_LINEAR,
int borderMode = BORDER_CONSTANT,
const Scalar & borderValue = Scalar()
)
参数解释
. src: 输入图像
. dst: 输出图像,尺寸由dsize指定,图像类型与原图像一致
. M: 2X3的变换矩阵
. dsize: 指定图像输出尺寸
. flags: 插值算法标识符,有默认值INTER_LINEAR,如果插值算法为WARP_INVERSE_MAP, warpAffine函数使用如下矩阵进行图像转换
. borderMode: 边界像素模式,有默认值BORDER_CONSTANT
. borderValue: 边界取值,有默认值Scalar()即0
代码:
# 图像旋转
def rotate_demo():
src = cv.imread("D://Image/lena.jpg")
cv.imshow("input", src)
dst = cv.rotate(src, cv.ROTATE_90_COUNTERCLOCKWISE)
dst2 = cv.flip(dst, 0)
cv.imshow("rotate", dst)
cv.imshow("dst2", dst2)
# 旋转任意角度
h, w, ch = src.shape
cy = h // 2
cx = w // 2
M = cv.getRotationMatrix2D((cx, cy), 45, 1.0) # 图像旋转的中心位置
print(M)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nw = np.int(h * sin + w * cos)
nh = np.int(h * cos + w * sin)
M[0, 2] += (nw / 2) - cx
M[1, 2] += (nh / 2) - cy
dst = cv.warpAffine(src, M, (nw, nh))
cv.imshow("output", dst)