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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3971459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:37:17  来源:igfitidea点击:

How to loop all image pixels and tell whether they are black or white

pythonpython-imaging-library

提问by Richard Knop

I have a simple black and white only gif image (400x400px let's say).

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

I need to get all pixels from that image and find whether they are black or white. I need to create a dictionary with the information about the pixels and their colors then.

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

I'm pretty new to python so I am kinda struggling with this. But here goes my script so far:

我对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)

Basically I want the final dictionary to be something like this:

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

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

EDIT:

编辑:

When I try:

当我尝试:

print aImage[0, 0]

I get an error:

我收到一个错误:

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__

采纳答案by Brian

You should be using getpixelrather than using indexing operators. Note that this may be very slow. You would be better off using getdata, which returns all of pixels as a sequence.

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

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

请参阅 http://effbot.org/imagingbook/image.htm

回答by Paulo Scardine

Try:

尝试:

pix = aImage.load()
print pix[x, y]

Also note that you can use tuples as dictionary keys, you can use mydict[(x, y)] instead of mydict["x,y"].

另请注意,您可以使用元组作为字典键,您可以使用 mydict[(x, y)] 而不是 mydict["x,y"]。

This pixel information is already stored in the image, why store it in a dict?

这个像素信息已经存储在图像中了,为什么还要存储在字典中呢?

回答by SamB

Are you sureyou want to do that? It would be horrendously inefficient to use a dictionary to store this data.

确定要这样做吗?使用字典来存储这些数据是非常低效的。

I would think a numpy array would be much more appropriate...

我认为 numpy 数组会更合适...

回答by Dantalion

If you wanted to see if a thumb was mono you could try this:-

如果你想看看拇指是否是单声道,你可以试试这个:-

def is_mono(image, variance=5):
    img_dta = list(im.getdata())   
    colour_test = lambda r,g,b : abs(r-g) > variance or abs(g-b) > variance
    if any([colour_test(r,g,b) for (r,g,b) in img_dta]):  return False
    return True

url1 = 'http://farm5.static.flickr.com/4145/5090947066_0d9d45edf4_s.jpg' # Mono
url2 = 'http://farm5.static.flickr.com/4087/5090362043_03c2da75d4_s.jpg' # Colour
for url in (url1, url2):
    dta = urllib.urlopen(url).read()
    im = Image.open(StringIO(dta))
    print is_mono(im)

>

>

True
False

回答by Thiago Druciaki

If you can ensure that your image is in black&white mode, you may do:

如果您可以确保您的图像处于黑白模式,则可以执行以下操作:

aPixelsBlackOrWhiteDictionary = {}
for y in range(0,aImage.size[1]):
    for x in range(0,aImage.size[0]):
        aPixelsBlackOrWhiteDictionary[ (x,y) ] = aImage.getpixel( (x,y) )

This uses the getpixelmentioned in other answers and the keyof your dictionary will be the tuple (x,y)

这使用了getpixel其他答案中提到的,您的字典的将是元组(x,y)

print aPixelsBlackOrWhiteDictionary
{(0, 1): 1, (1, 2): 1, (3, 2): 0, (0, 0): 0, (3, 3): 1, (3, 0): 0, (3, 1): 1, (2, 1): 0, (0, 2): 0, (2, 0): 1, (1, 3): 0, (2, 3): 0, (2, 2): 1, (1, 0): 1, (0, 3): 1, (1, 1): 0}

verify that getpixelis returning ones and zeros

验证getpixel返回 1 和 0