python代码,对图像进行仿射变换,改变形态
- User
python代码,对图像进行仿射变换,改变形态
Assistant
我来帮你写一个使用OpenCV进行图像仿射变换的Python代码示例。这个代码会展示几种常见的仿射变换效果:
import cv2 import numpy as np def affine_transform_demo(image_path): # 读取图像 img = cv2.imread(image_path) rows, cols = img.shape[:2] # 1. 平移变换 M_translation = np.float32([[1, 0, 50], [0, 1, 30]]) translated = cv2.warpAffine(img, M_translation, (cols, rows)) # 2. 旋转变换 angle = 45 M_rotation = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1) rotated = cv2.warpAffine(img, M_rotation, (cols, rows)) # 3. 缩放变换 src_points = np.float32([[0, 0], [cols-1, 0], [0, rows-1]]) dst_points = np.float32([[cols*0.2, rows*0.1], [cols*0.8, rows*0.2], [cols*0.1, rows*0.9]]) M_affine = cv2.getAffineTransform(src_points, dst_points) affine = cv2.warpAffine(img, M_affine, (cols, rows)) # 显示结果 cv2.imshow('Original', img) cv2.imshow('Translated', translated) cv2.imshow('Rotated', rotated) cv2.imshow('Affine', affine) cv2.waitKey(0) cv2.destroyAllWindows() # 使用示例 image_path = 'your_image.jpg' # 替换为你的图片路径 affine_transform_demo(image_path)这段代码实现了三种仿射变换:
- 平移变换:将图像向右移动50像素,向下移动30像素
- 旋转变换:将图像绕中心点旋转45度
- 仿射变换:通过指定三个点的原始位置和目标位置进行变换
要使用这段代码,你需要:
- 安装必要的库:
pip install opencv-python numpy- 将
image_path替换为你实际的图片路径
如果你想要调整变换效果,可以修改以下参数:
- 平移:修改
M_translation中的[50, 30]值 - 旋转:修改
angle的值 - 仿射:修改
dst_points中的坐标值
你还可以添加其他类型的仿射变换,比如:
# 添加缩放变换 scale = 1.5 M_scale = np.float32([[scale, 0, 0], [0, scale, 0]]) scaled = cv2.warpAffine(img, M_scale, (int(cols*scale), int(rows*scale)))这个代码会帮助你理解和实现基本的图像仿射变换。需要注意的是,仿射变换会保持平行线之间的平行关系,但可能会改变角度和距离。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.