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

时间:2010-10-19 18:29:47

标签: python python-imaging-library

我有一个简单的黑白gif图像(400x400px让我们说)。

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

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

5 个答案:

答案 0 :(得分:7)

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

  

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

答案 1 :(得分:4)

尝试:

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

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

此像素信息已存储在图像中,为什么要将其存储在字典中?

答案 2 :(得分:1)

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

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)
  
    

&GT;

  
True
False

答案 3 :(得分:0)

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

public class kanvas1 implements ActionListener,WindowListener{


    private JTextField tf;
    private JTextField tf1;
    private JTextField tf2;
    private JTextField tf3;
    private JLabel lb;
    private JLabel lb1;

    private JButton bt;
    private JButton bt1;

    public kanvas1()
    {

        tf=new JTextField();
        tf1=new JTextField();
        tf2=new JTextField();
        tf3=new JTextField();
        lb=new JLabel("$");
        lb1=new JLabel("TL");
        bt=new JButton("Cevir");
        bt1=new JButton("Sıfırla");


        pencere();


    }

    public void pencere() {
        tf.setBounds(50,20,150,50);
        tf1.setBounds(50,80, 150, 50);
        tf2.setBounds(220,20,150,50);
        tf3.setBounds(220,80,150,50);
        lb.setBounds(30,20,20, 50);
        lb1.setBounds(30,80,20,50);
        bt.setBounds(400,20,100, 50);
        bt1.setBounds(400,80,100,50);
        bt.addActionListener(this);
        bt1.addActionListener(this);
        JFrame ab=new JFrame();
        ab.setVisible(true);
        ab.setSize(600,200);
        ab.setLayout(null);
        ab.add(tf);ab.add(tf1);ab.add(tf2);ab.add(tf3);ab.add(bt);ab.add(bt1);ab.add(lb);ab.add(lb1);
        bt.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {


                String s=tf.getText(); //problem is here


                double a=Double.parseDouble(s);

                double c=a*5.44;

                String result=String.valueOf(c);

                tf2.setText(result);




            }

        });
        bt.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {



                String s1=tf1.getText();
                                          //and here

                double b=Double.parseDouble(s1);

                double d=b*0.18;

                String result1=String.valueOf(d);

                tf3.setText(result1);


            }

        });
        bt1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                tf.setText("");
                tf1.setText("");
                tf2.setText("");
                tf3.setText("");

            }
        });


    }


    @Override
    public void windowActivated(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowClosed(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowClosing(WindowEvent arg0) {
        System.exit(0);

    }

    @Override
    public void windowDeactivated(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowDeiconified(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowIconified(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowOpened(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    public static void main(String args[]) {

        new kanvas1();



    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }   
}

这将使用其他答案中提到的aPixelsBlackOrWhiteDictionary = {} for y in range(0,aImage.size[1]): for x in range(0,aImage.size[0]): aPixelsBlackOrWhiteDictionary[ (x,y) ] = aImage.getpixel( (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} 是否返回1和0

答案 4 :(得分:-2)

确定你想这样做吗?使用字典存储这些数据会非常低效。

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