Anh Nguyen
Anh Nguyen

Reputation: 27

Loop through all pixels of 2 images and replace the black pixels with white

I have 2 co-located images, both created in a similar way and both have the size of 7,221 x 119 pixels.

I want to loop through all the pixels of both images. If the pixels are black on the first image and also black on the second image then turn it into white, otherwise, no change.

How can I do it with python?

Upvotes: 0

Views: 1787

Answers (2)

pyInTheSky
pyInTheSky

Reputation: 1479

This should hopefully be pretty close to what you're looking for.

from PIL import Image
from PIL import ImageFilter

im            = Image.open('a.png')
imb           = Image.open('b.png')
pix           = im.load()
width, height = im.size
for w in xrange(width):
    for h in xrange(height):
        r,g,b,a = pix[(w,h)]
        rb, gb, bb, ab = pix[(w,h)]
        if not (r+g+b+rb+gb+bb): #all values 0
            pix[w,h] = (255,255,255,255)
im.save('test','BMP')

Upvotes: 0

B B
B B

Reputation: 1196

I suggest the use of the Pillow library (https://python-pillow.org/) which is a fork of the PIL library.

Here's something from the Pillow docs: http://pillow.readthedocs.io/en/3.1.x/reference/PixelAccess.html

And a couple of Stackoverflow questions that may help you:

Is it possible to change the color of one individual pixel in Python?

Changing pixel color Python

I guess you'd just have to open both images, loop through each pixel of rach image, compare the pixels, compare pixels, then replace if necessary.

Upvotes: 0

Related Questions