opencv对图片进行随机裁剪并将裁剪后的图片调整到指定大小 请代码举例
时间: 2024-05-13 07:13:43 浏览: 174
好的,以下是用OpenCV进行随机裁剪并将裁剪后的图片调整到指定大小的Python代码示例:
```python
import cv2
import numpy as np
def random_crop(image, target_size):
height, width = image.shape[:2]
target_height, target_width = target_size
# 随机选择裁剪位置
x = np.random.randint(0, width - target_width + 1)
y = np.random.randint(0, height - target_height + 1)
# 进行裁剪
cropped_image = image[y:y+target_height, x:x+target_width]
return cropped_image
def resize(image, target_size):
resized_image = cv2.resize(image, target_size)
return resized_image
# 读取图片
image = cv2.imread('test.jpg')
# 进行随机裁剪
cropped_image = random_crop(image, (256, 256))
# 调整图片大小
resized_image = resize(cropped_image, (128, 128))
# 显示结果
cv2.imshow('original', image)
cv2.imshow('cropped', cropped_image)
cv2.imshow('resized', resized_image)
cv2.waitKey(0)
```
这段代码将读取名为“test.jpg”的图片,并随机裁剪为256x256大小,然后将裁剪后的图片调整为128x128大小,并分别显示原始图片、裁剪后的图片和调整后的图片。
阅读全文