如何在Python中随机选择图像的一部分

0 投票
1 回答
1869 浏览
提问于 2025-04-17 07:57

假设我有一张很大的图片(5000 x 5000像素),我想从这张大图片中随机选取一部分(200 x 200像素的正方形)。另外,我还想设置一些边界,确保选取的区域不会超出这张图片的范围。

如果有人有好的主意,请分享一下。

1 个回答

5
import random

image_size = (5000,5000)
portion_size = (200, 200)

x1 = random.randint(0, image_size[0]-portion_size[0]-1)
y1 = random.randint(0, image_size[1]-portion_size[1]-1)

x2, y2 = x1+portion_size[0]-1, y1+portion_size[1]-1

# Grab the area of the image that is the rectangle defined by (x1,y1) and (x2,y2)

你最后一步怎么做,取决于你是怎么处理这个图片的。

撰写回答