python根据标出的矩形框剪裁图片
时间: 2023-10-23 13:08:48 浏览: 35
可以使用PIL库来实现图片的剪裁。具体步骤如下:
1. 导入PIL库和numpy库
```python
from PIL import Image
import numpy as np
```
2. 打开图片并转换为numpy数组
```python
img = Image.open('image.jpg')
img_array = np.array(img)
```
3. 根据矩形框的坐标剪裁图片
```python
x1, y1, x2, y2 = 100, 100, 300, 300 # 矩形框的坐标
cropped_img_array = img_array[y1:y2, x1:x2]
```
4. 将剪裁后的numpy数组转换为PIL Image对象
```python
cropped_img = Image.fromarray(cropped_img_array)
```
5. 保存剪裁后的图片
```python
cropped_img.save('cropped_image.jpg')
```
完整代码如下:
```python
from PIL import Image
import numpy as np
img = Image.open('image.jpg')
img_array = np.array(img)
x1, y1, x2, y2 = 100, 100, 300, 300
cropped_img_array = img_array[y1:y2, x1:x2]
cropped_img = Image.fromarray(cropped_img_array)
cropped_img.save('cropped_image.jpg')
```