我假设你得到一个错误,比如TypeError: 'PixelAccess' object is not iterable
......?
有关如何访问像素的信息,请参阅Image.load文档。
基本上,要获取图像中的像素列表,请使用PIL
:
from PIL import Image
i = Image.open("myfile.png")
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size
all_pixels = []
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
all_pixels.append(cpixel)
这会将每个像素附加到all_pixels
- 如果文件是 RGB 图像(即使它只包含黑白图像),这些将是一个元组,例如:
(255, 255, 255)
要将图像转换为单色,只需平均三个值 - 因此,最后三行代码将变为..
cpixel = pixels[x, y]
bw_value = int(round(sum(cpixel) / float(len(cpixel))))
# the above could probably be bw_value = sum(cpixel)/len(cpixel)
all_pixels.append(bw_value)
或获得亮度(加权平均):
cpixel = pixels[x, y]
luma = (0.3 * cpixel[0]) + (0.59 * cpixel[1]) + (0.11 * cpixel[2])
all_pixels.append(luma)
或纯 1 位的黑白:
cpixel = pixels[x, y]
if round(sum(cpixel)) / float(len(cpixel)) > 127:
all_pixels.append(255)
else:
all_pixels.append(0)
PIL 中可能有一些方法可以RGB -> BW
更快地进行此类转换,但这很有效,而且不是特别慢。
如果您只想对每一行执行计算,则可以跳过将所有像素添加到中间列表。例如,要计算每一行的平均值:
from PIL import Image
i = Image.open("myfile.png")
pixels = i.load() # this is not a list
width, height = i.size
row_averages = []
for y in range(height):
cur_row_ttl = 0
for x in range(width):
cur_pixel = pixels[x, y]
cur_pixel_mono = sum(cur_pixel) / len(cur_pixel)
cur_row_ttl += cur_pixel_mono
cur_row_avg = cur_row_ttl / width
row_averages.append(cur_row_avg)
print "Brighest row:",
print max(row_averages)