如何使用 PIL 从 PNG 文件中取出每一个可能的 n 大小的正方形?

How to take every possible n-size square from PNG file with PIL?

我想加载图像,从 png 文件中裁剪每个可能的给定大小(取自用户)的正方形,并打印每个给定裁剪的平均 RGB 值。现在我的代码如下所示:

from PIL import Image
from statistics import mean

print("Input height: ")
crop_height = int(input())

print("Input width: ")
crop_width = int(input())
image = Image.open('daisy/5547758_eea9edfd54_n.jpg')
print(image.size)
image_height, image_width = image.size
for y in range(0, image_height-crop_height):
    for x in range(0, image_width-crop_width):
        box = (x, y, crop_width, crop_height)
        print(box)
        cropped_image = image.crop(box)
        average_color = [round(mean(cropped_image.getdata(band))) for band in range(3)]
        print("RGB: ", average_color)

我针对 32x32 正方形进行测试。我怎样才能做到这一点 ?现在我收到这个错误。

Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\testMap\RGBAvg.py", line 19, in <module>
    average_color = [round(mean(cropped_image.getdata(band))) for band in range(3)]
  File "C:\Users\Damian\PycharmProjects\testMap\RGBAvg.py", line 19, in <listcomp>
    average_color = [round(mean(cropped_image.getdata(band))) for band in range(3)]
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\statistics.py", line 315, in mean
    raise StatisticsError('mean requires at least one data point')
statistics.StatisticsError: mean requires at least one data point

您正在将空列表传递给 mean() - 获取列表并在传递给 mean() 之前检查其长度,如果它为空则跳出循环。