How to implement image rotation and flipping in OpenCV?

In OpenCV, you can use functions to rotate and flip images. Here is a commonly used method:

Image rotation: Image rotation can cv2.warpAffine()be achieved through functions. This function can rotate the image according to the specified rotation angle, rotation center and image size.

Sample code:

import cv2
import numpy as np

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

# 获取图像宽度和高度
height, width = image.shape[:2]

# 定义旋转角度和旋转中心
angle = 45  # 旋转角度
center = (width // 2, height // 2)  # 旋转中心

# 计算旋转矩阵
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)

# 进行图像旋转
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))

# 显示旋转后的图像
cv2.imshow('Rotated Image', rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
  1. Image flipping: Image flipping can cv2.flip()be achieved through functions. This function can flip an image horizontally or vertically, or both horizontally and vertically. How to implement image rotation and flipping in OpenCV?

Sample code:

import cv2

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

# 进行水平翻转
flipped_horizontal = cv2.flip(image, 1)

# 进行垂直翻转
flipped_vertical = cv2.flip(image, 0)

# 进行水平和垂直翻转
flipped_both = cv2.flip(image, -1)

# 显示翻转后的图像
cv2.imshow('Flipped Horizontal', flipped_horizontal)
cv2.imshow('Flipped Vertical', flipped_vertical)
cv2.imshow('Flipped Both', flipped_both)
cv2.waitKey(0)
cv2.destroyAllWindows()

The above is a brief introduction to image rotation and flipping in OpenCV. According to the specific needs, you can choose the appropriate method and parameters to adjust to obtain the desired rotation and flip effects.

Compiled information about artificial intelligence, including image processing opencv\natural language processing, machine learning, mathematical foundation and other artificial intelligence information, deep learning neural network + CV computer vision learning (two major frameworks pytorch/tensorflow + source free to provide free attention v❤ Public H: AI technology planet reply code 123 

Guess you like

Origin blog.csdn.net/m0_74693860/article/details/131323435