opencv库(1)

图像变换

图像的平移、旋转、镜像、缩放、仿射变换、透视变换

import cv2 as cv
import numpy as np

img = cv.imread("img.png", cv.IMREAD_GRAYSCALE)
rows, cols = img.shape
# 平移
# x方向移动100像素,y方向移动50像素
M1 = np.array([[1, 0, 100], [0, 1, 50]], np.float32)
img_shift = cv.warpAffine(img, M1, (cols, rows))
# 旋转
# 以程序左上角为原点,顺时针旋转45度
M2 = np.array([[np.cos(45), -np.sin(45), 0], [np.sin(45), np.cos(45), 0]], np.float32)
img_rotate = cv.warpAffine(img, M2, (cols, rows))
# 镜像
# 水平方向
M3 = np.array([[-1, 0, cols], [0, 1, 0]], np.float32)
img_mirror_h = cv.warpAffine(img, M3, (cols, rows))
# 垂直方向
M4 = np.array([[1, 0, 0], [0, -1, rows]], np.float32)
img_mirror_v = cv.warpAffine(img, M4, (cols, rows))
# 缩放
M5 = np.array([[0.5, 0, 0], [0, 0.5, 0]], np.float32)
img_scale = cv.warpAffine(img, M5, (cols, rows))
# 仿射变换
pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])
M6 = cv.getAffineTransform(pts1, pts2)
img_affine = cv.warpAffine(img, M6, (cols, rows))
# 透视变换
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
M7 = cv.getPerspectiveTransform(pts1,pts2)
img_perspective = cv.warpPerspective(img,M7,(300,300))

Guess you like

Origin blog.csdn.net/weixin_49346755/article/details/121053808