gpt4 book ai didi

python - 如何循环所有图像像素并判断它们是黑色还是白色

转载 作者:太空狗 更新时间:2023-10-30 01:56:00 26 4
gpt4 key购买 nike

我有一个简单的黑白 gif 图片(假设为 400x400 像素)。

我需要从该图像中获取所有像素并确定它们是黑色还是白色。然后我需要创建一个包含有关像素及其颜色的信息的字典。

我是 python 的新手,所以我有点挣扎。但到目前为止我的脚本是这样的:

#!/usr/bin/env python

import os
import Image

os.chdir("D:/python-projects")
aImage = Image.open("input.gif")

aPixelsBlackOrWhiteDictionary = {}
# now I need to fill the dictionary with values such as
# "X,Y": 0
# "X,Y": 1
# where X,Y are coordinates and 0/1 i the pixel color (b/w)

基本上我希望最终的字典是这样的:

"0,0" : 0 # pixel with X=0,Y=0 coordinates is black
"1,0" : 1 # pixel with X=1,Y=0 coordinates is White

编辑:

当我尝试时:

print aImage[0, 0]

我得到一个错误:

Traceback (most recent call last):
File "D:\python-projects\backprop.py", line 15, in <module>
print aImage[0, 0]
File "C:\Python26\lib\site-packages\pil-1.1.7-py2.6-win32.egg\Image.py", line
512, in __getattr__
raise AttributeError(name)
AttributeError: __getitem__

最佳答案

您应该使用 getpixel 而不是使用索引运算符。请注意,这可能非常慢。您最好使用 getdata,它将所有像素作为一个序列返回。

See http://effbot.org/imagingbook/image.htm .

关于python - 如何循环所有图像像素并判断它们是黑色还是白色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com