import cv2 import numpy as np # 读取原始图像 img = cv2.imread('image.webp') # 缩放变换 scale_percent = 50 # 缩放比例 width = int(img.shape[1] * scale_percent / 100) # 新图像宽度 height = int(img.shape[0] * scale_percent / 100) # 新图像高度 dim = (width, height) resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) # 旋转变换 angle = 45 # 旋转角度 rotation_matrix = cv2.getRotationMatrix2D((img.shape[1]/2, img.shape[0]/2), angle, 1) rotated = cv2.warpAffine(img, rotation_matrix, (img.shape[1], img.shape[0])) # 平移变换 x = 50 # 水平方向平移像素数 y = 100 # 垂直方向平移像素数 translation_matrix = np.float32([[1, 0, x], [0, 1, y]]) translated = cv2.warpAffine(img, translation_matrix, (img.shape[1], img.shape[0])) # 裁剪变换 x1 = 100 # 左上角横坐标 y1 = 100 # 左上角纵坐标 x2 = 300 # 右下角横坐标 y2 = 300 # 右下角纵坐标 cropped = img[y1:y2, x1:x2] # 镜像变换 mirrored = cv2.flip(img, 1) # 在同一个窗口内分成六个子窗口来分别显示原图和变换后的图像 cv2.namedWindow('Image', cv2.WINDOW_NORMAL) cv2.resizeWindow('Image', 700, 700) cv2.imshow('Image', np.vstack((img, resized, rotated, translated, cropped, mirrored))) cv2.waitKey(0) cv2.destroyAllWindows()优化这段代码,并显示结果图
时间: 2024-01-07 17:05:18 浏览: 193
可以将这段代码封装成一个函数,并将变换操作作为参数传递给函数,以避免代码重复。以下是一个示例:
```python
import cv2
import numpy as np
def apply_transformations(img, transformations):
transformed_images = []
for transformation in transformations:
if transformation == 'resize':
scale_percent = 50
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
transformed_images.append(resized)
elif transformation == 'rotate':
angle = 45
rotation_matrix = cv2.getRotationMatrix2D((img.shape[1]/2, img.shape[0]/2), angle, 1)
rotated = cv2.warpAffine(img, rotation_matrix, (img.shape[1], img.shape[0]))
transformed_images.append(rotated)
elif transformation == 'translate':
x = 50
y = 100
translation_matrix = np.float32([[1, 0, x], [0, 1, y]])
translated = cv2.warpAffine(img, translation_matrix, (img.shape[1], img.shape[0]))
transformed_images.append(translated)
elif transformation == 'crop':
x1 = 100
y1 = 100
x2 = 300
y2 = 300
cropped = img[y1:y2, x1:x2]
transformed_images.append(cropped)
elif transformation == 'mirror':
mirrored = cv2.flip(img, 1)
transformed_images.append(mirrored)
return transformed_images
# 读取原始图像
img = cv2.imread('image.webp')
# 定义要应用的变换
transformations = ['resize', 'rotate', 'translate', 'crop', 'mirror']
# 应用变换并显示结果图像
transformed_images = apply_transformations(img, transformations)
cv2.namedWindow('Transformed Images', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Transformed Images', 1200, 800)
cv2.imshow('Transformed Images', np.hstack(transformed_images))
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个函数将原始图像和要应用的变换作为参数,返回一个包含所有变换后图像的列表。通过调用这个函数并将返回的结果合并成一张图像,就可以显示所有变换后的图像。
阅读全文