简体   繁体   中英

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?

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM