Python OpenCv 仿射变换、平移、旋转、缩放、透视变换
仿射变换
import cv2 import numpy img = cv2.imread("D:/test123.png") rows, cols = img.shape[:2] p1 = numpy.float32([[0, 0], [cols - 1, 0], [0, rows - 1]]) p2 = numpy.float32([[0, rows * 0.3], [cols * 0.8, rows * 0.5], [cols * 0.2, rows * 0.7]]) M = cv2.getAffineTransform(p1, p2) res = cv2.warpAffine(img, M, (cols, rows)) cv2.imshow("测试1", img) cv2.imshow("测试2", res) cv2.waitKey() cv2.destroyAllWindows()
平移
import cv2 import numpy img = cv2.imread("D:/test11.png") rows, cols = img.shape[:2] p1 = numpy.float32([[0, 0], [cols - 1, 0], [0, rows - 1]]) p2 = numpy.float32([[25, 40], [cols - 1 + 25, 40], [25, rows - 1 + 40]]) M = cv2.getAffineTransform(p1, p2) res = cv2.warpAffine(img, M, (cols, rows)) cv2.imshow("测试1", img) cv2.imshow("测试2", res) cv2.waitKey() cv2.destroyAllWindows()
平移快捷方式
import cv2 import numpy img = cv2.imread("D:/test11.png") rows, cols = img.shape[:2] M = numpy.float32([[1, 0, 25], [0, 1, 40]]) res = cv2.warpAffine(img, M, (cols, rows)) cv2.imshow("测试1", img) cv2.imshow("测试2", res) cv2.waitKey() cv2.destroyAllWindows()
旋转
import cv2 import numpy img = cv2.imread("D:/test11.png") rows, cols = img.shape[:2] p1 = numpy.float32([[0, 0], [cols - 1, 0], [0, rows - 1]]) p2 = numpy.float32([[25, 40], [cols - 1 + 25, 40], [25, rows - 1 + 40]]) M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 45, 1)#中心点, 45°角, 缩放比例1 res = cv2.warpAffine(img, M, (cols, rows)) cv2.imshow("测试1", img) cv2.imshow("测试2", res) cv2.waitKey() cv2.destroyAllWindows()
缩放
import cv2 img = cv2.imread("D:/test11.png") res = cv2.resize(img, (300, 200)) cv2.imshow("测试1", img) cv2.imshow("测试2", res) cv2.waitKey() cv2.destroyAllWindows()
透视变换
import cv2 import numpy img = cv2.imread("D:/test11.png") rows, cols = img.shape[:2] p1 = numpy.float32([[0, 0], [cols - 1, 0], [0, rows - 1], [cols - 1, rows - 1]]) p2 = numpy.float32([[0, rows * 0.3], [cols * 0.8, rows * 0.5], [cols * 0.2, rows * 0.7], [cols * 0.8, rows * 0.8]]) M = cv2.getPerspectiveTransform(p1, p2) res = cv2.warpPerspective(img, M, (cols, rows)) cv2.imshow("测试1", img) cv2.imshow("测试2", res) cv2.waitKey() cv2.destroyAllWindows()