以下是使用 Python 对图像进行旋转和翻转的示例代码:

import cv2

# 读取图像
img = cv2.imread('image.jpg')

# 图像旋转
img_rot90 = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
img_rot180 = cv2.rotate(img, cv2.ROTATE_180)
img_rot270 = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)

# 图像翻转
img_flip_ud = cv2.flip(img, 0)  # 上下翻转
img_flip_lr = cv2.flip(img, 1)  # 左右翻转

# 显示图像
cv2.imshow('Original Image', img)
cv2.imshow('Rotated 90 Degrees', img_rot90)
cv2.imshow('Rotated 180 Degrees', img_rot180)
cv2.imshow('Rotated 270 Degrees', img_rot270)
cv2.imshow('Flipped Up-Down', img_flip_ud)
cv2.imshow('Flipped Left-Right', img_flip_lr)

# 等待按键
cv2.waitKey(0)

# 关闭窗口
cv2.destroyAllWindows()

在代码中,我们首先使用cv2.imread()函数读取一张图像,然后使用cv2.rotate()cv2.flip()函数对图像进行旋转和翻转。其中,cv2.rotate()函数接受一个旋转角度作为参数,可以实现 90 度、180 度和 270 度的旋转;cv2.flip()函数接受一个翻转方向作为参数,可以实现上下翻转和左右翻转。最后,我们使用cv2.imshow()函数将图像显示出来,并使用cv2.waitKey()函数等待按键,最后使用cv2.destroyAllWindows()函数关闭窗口。

注意,在使用cv2.imshow()函数显示图像之前,需要确保图像已经被正确读取,否则可能会出现显示异常的情况。另外,在进行图像旋转和翻转时,需要注意图像的尺寸和比例是否发生变化,以免影响后续处理。

Python 图像旋转和翻转:90°、180°、270° 旋转及上下左右翻转

原文地址: https://www.cveoy.top/t/topic/nUgm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录