自己编写程序读入一幅图像,然后使用 cv2.warpAffine()函数该对图 像做以下变换:平移、放缩、旋转、平移+放缩、放缩+旋转、平移+旋转+放缩, 最后显示各种变换后的图像效果
时间: 2024-11-22 16:37:41 浏览: 5
在Python中,我们可以使用OpenCV库的`cv2.warpAffine()`函数来对图像进行各种几何变换。首先,你需要读入图像,例如:
```python
import cv2
img = cv2.imread('your_image_path.jpg')
```
接下来,你可以创建一个仿射变换矩阵来执行上述变换。每个变换类型对应不同的变换矩阵:
1. **平移 (Translation)**:
```python
rows, cols, _ = img.shape
M = np.float32([[1, 0, col_shift], [0, 1, row_shift]])
```
2. **放缩 (Scaling)**:
```python
scale_factor = 0.5 # 缩小一半
M = np.float32([[scale_factor, 0, -(cols*scale_factor)], [0, scale_factor, -(rows*scale_factor)]])
```
3. **旋转 (Rotation)**:
```python
angle_degrees = 45 # 逆时针45度
center = (cols//2, rows//2)
M = cv2.getRotationMatrix2D(center, -angle_degrees, 1.0)
```
4. **组合变换**:
- 平移+放缩:
```python
M = np.float32([[scale_factor, 0, col_shift*scale_factor], [0, scale_factor, row_shift*scale_factor]])
```
- 放缩+旋转:
```python
M = np.concatenate((np.array([[scale_factor, 0, -(col_shift*scale_factor)], [0, scale_factor, -(row_shift*scale_factor)]]), [[0, 0, 1]]), axis=1)
```
- 平移+旋转+放缩:
```python
M = np.concatenate((np.array([[scale_factor, 0, col_shift*scale_factor], [0, scale_factor, row_shift*scale_factor]]), [[0, 0, 1]]), axis=1)
M = cv2.getRotationMatrix2D(center, -angle_degrees, 1.0)
```
然后应用变换到原图像,并显示结果:
```python
warped_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
cv2.imshow('Original', img)
cv2.imshow('Transformed', warped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文