dgrat
dgrat

Reputation: 2244

Python Imaging Library: Cannot access pixel values

I want to compare two images and save a difference image, where the differences are marked in red. Unfortunately I get the following error:

Traceback (most recent call last):
  File "pythontest.py", line 216, in <module>
    nDiff = compare(sPathCur, sPathRef, sPathDif)
  File "pythontest.py", line 88, in compare
    pix_diff[y, x] = (255, 0, 0)
TypeError: function takes exactly 1 argument (3 given)
def compare(sPathCur, sPathRef, sPathDif):
    im_cur = Image.open(sPathCur)
    im_ref = Image.open(sPathRef)

    im_dif = im_cur.convert('L')  # convert image to grey scale

    delta = ImageChops.difference(im_cur, im_ref)
    width, height = delta.size

    pix_delta = delta.load()
    pix_diff = im_dif.load()

    for y in range(width):
        for x in range(height):
            r, g, b = pix_delta[y, x]
            if (r > 0 or g > 0 or b > 0):
                pix_diff[y, x] = (255, 0, 0)

    im_dif.save(sPathDif)

Upvotes: 0

Views: 38

Answers (1)

DatHydroGuy
DatHydroGuy

Reputation: 1116

Once you have performed the conversion to a greyscale image, each pixel is assigned a single value, rather than an RGB triplet.

Taken from http://effbot.org/imagingbook/image.htm :

When converting from a colour image to black and white, the library uses the ITU-R 601-2 luma transform:

L = R * 299/1000 + G * 587/1000 + B * 114/1000

So if your pixel at [x,y]=[0,0] had (R,G,B) value of (100,150,200), then after converting to greyscale, it would contain the single value 140.75 (which would then be rounded to an integer)

You can verify this by checking the value of pix_diff[0,0] before your nested loops. It should return you only a single value.

So you either need to assign a single greyscale value to each pixel in your pix_diff[y, x], or convert your pix_diff image back into an RGB-compatible format before you can assign each pixel your value of (255, 0, 0)

Upvotes: 1

Related Questions