在Python中选择图像的一部分(不使用imcrop)

2024-04-25 00:39:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想选择图像的一部分并将其保存为图像文件,但我不想使用imcrop()功能。那里有很多答案,但我不想用作物功能。有吗其他方法?你知道吗


Tags: 方法答案作物图像功能图像文件imcrop
1条回答
网友
1楼 · 发布于 2024-04-25 00:39:26

您可以将其转换为数组,并通过索引“裁剪”它,然后再转换回图像。你知道吗

from PIL import Image
import numpy as np

# Create an image for example
w, h = 512, 512 
data = np.zeros((h, w, 3), dtype=np.uint8)
data[:, :, :] = 100  # Grey image
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()  # View the original image

img_array = np.asarray(img)  # Convert image to an array
cropped = img_array[:100, :100, :]  # Select portion to keep

img = Image.fromarray(cropped, 'RGB')  # Convert back to image
img.save('my.png')
img.show()  # View the cropped image

相关问题 更多 >