52 lines
2.0 KiB
Python
52 lines
2.0 KiB
Python
# 用opencv对一图片完成平移(X方向20px,Y方向20px)、缩小(0.5倍)、放大(2倍)、旋转(逆时针90度)、翻转(水平)、仿射(任意)、透视(任意)操作,所有操作后与原图保持相同大小
|
|
|
|
import cv2 as cv
|
|
import numpy as np
|
|
|
|
image = cv.imread('img.jpg', cv.IMREAD_UNCHANGED)
|
|
|
|
height, width = image.shape[:2]
|
|
|
|
# 1.平移
|
|
M_translate = np.float32([[1, 0, 20], [0, 1, 20]])
|
|
image_translate = cv.warpAffine(image, M_translate, (width, height))
|
|
|
|
# 2.缩小操作(0.5倍)
|
|
image_resized_small = cv.resize(image, (0, 0), fx=0.5, fy=0.5)
|
|
|
|
# 3.放大操作(2倍)
|
|
image_resized_large = cv.resize(image, (0, 0), fx=2, fy=2)
|
|
|
|
# 4.旋转操作(逆时针90度)
|
|
M_rotate = cv.getRotationMatrix2D((width / 2, height / 2), -90, 1)
|
|
image_rotated = cv.warpAffine(image, M_rotate, (width, height))
|
|
|
|
# 5.翻转操作(水平翻转)
|
|
image_flipped = cv.flip(image, 1)
|
|
|
|
# 6.仿射变换(任意)
|
|
# 三个点的原图与目标图像对应
|
|
pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
|
|
pts2 = np.float32([[10, 100], [250, 50], [100, 250]])
|
|
M_affine = cv.getAffineTransform(pts1, pts2)
|
|
image_affine = cv.warpAffine(image, M_affine, (width, height))
|
|
|
|
# 7.透视变换(任意)
|
|
# 四个点的原图与目标图像对应
|
|
pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
|
|
pts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]])
|
|
M_perspective = cv.getPerspectiveTransform(pts1, pts2)
|
|
image_perspective = cv.warpPerspective(image, M_perspective, (width, height))
|
|
|
|
# 展示
|
|
cv.imshow('原图', image)
|
|
cv.imshow('1.平移', image_translate)
|
|
cv.imshow('2.缩小操作(0.5倍)', image_resized_small)
|
|
cv.imshow('3.放大操作(2倍)', image_resized_large)
|
|
cv.imshow('4.旋转操作(逆时针90度)', image_rotated)
|
|
cv.imshow('5.翻转操作(水平翻转)', image_flipped)
|
|
cv.imshow('6.仿射变换(任意)', image_affine)
|
|
cv.imshow('7.透视变换(任意)', image_perspective)
|
|
cv.waitKey(0)
|
|
cv.destroyAllWindows()
|