How do you compare pixels?

I use PIL to make an image with a black background and make a mask out of it. What I want the program to do is iterate over all the pixels of the image and if the pixel is black it makes it white and if it is some other color it makes it black, but I'm not sure how to compare the pixel values ​​correctly so that determine what to do with the pixel.

Here is my code so far that creates the entire black image.

import os, sys
import Image

filename = "C:\Users\pdiffley\Dropbox\C++2\Code\Test\BallSpriteImage.bmp"
height   = 50
width    = 50


im = Image.open(filename)
im = im.load()

i = 0
j = 0
while i<height:
    while j<width:
        if im[j,i] == (0,0,0):
            im[j,i] = (255,255,255)
        else:
            im[j,i] = (0,0,0) 
        j = j+1
    i = i+1
mask = Image.new('RGB', (width, height))
newfile = filename.partition('.')
newfile = newfile[0] + "Mask.bmp"

mask.save(newfile)

I believe the problem lies in the if statement, comparing im [j, i] with the RGB value (0,0,0), which is always evaluated as false. What is the correct way to compare a pixel?

+3
source share
3 answers

Comparing pixel data is correct. But there are two problems with the logic:

  • , reset j 0.
  • "im", "".

( -, andrewdski):

img = Image.open(filename)
im = img.load()

i = 0
while i<height:
    j = 0
    while j<width:
        if im[j,i] == (0,0,0):
            im[j,i] = (255,255,255)
        else:
            im[j,i] = (0,0,0) 
        j = j+1
    i = i+1
newfile = filename.partition('.')
newfile = newfile[0] + "Mask.png"

img.save(newfile)
+4

.point :

CVT_TABLE= (255,) + 255 * (0,)

def do_convert(img):
    return img.point(CVT_TABLE * len(img.getbands()))

, , : new Battlestar Galactica poster
:
colorful result

, , "L":

CVT_TABLE= (255,) + 255 * (0,)

def do_convert(img):
    return img.convert("L").point(CVT_TABLE)

:
almost but not quite

, (, #000001, ), , .

+1

Here, as I rewrote it, which avoids the problem with the reset pixel index using loops for, writes data to a separate image of the mask, and not back to the source, and removes the size of the hard-set size. I also added a prefix rto the file name string to handle backslashes in it.

import os, sys
import Image

BLACK = (0,0,0)
WHITE = (255, 255, 255)

filename = r"C:\Users\pdiffley\Dropbox\C++2\Code\Test\BallSpriteImage.bmp"

img = Image.open(filename)
width, height = img.size
im = img.load()

mask = Image.new('RGB', (width, height))
msk = mask.load()

for y in xrange(height):
    for x in xrange(width):
        if im[x,y] == BLACK:
            msk[x,y] = WHITE
        else:  # not really needed since mask initial color is black
            msk[x,y] = BLACK

newfilename = filename.partition('.')
newfilename = newfilename[0] + "Mask.bmp"
mask.save(newfilename)
+1
source

All Articles