Search code examples
pythonimagepng

i want to change every single pixel of an img to black exluding transparent python


I want to edit all the pixels of a PNG image except for the transparent pixels. I have this code:

    img_da_maskerare = Image.open("temp.png")
    width = img_da_maskerare.size[0] 
    height = img_da_maskerare.size[1] 
    for i in range(0,width):
        for j in range(0,height):
            data = img_da_maskerare.getpixel((i,j))
            #print(data) #(255, 255, 255)
            if (data[0]!=255 and data[1]!=0 and data[2]!=0):
                img_da_maskerare.putpixel((i,j),(00, 00, 00))
    img_da_maskerare.show() 

example: original becomes this

What is wrong with the code?


Solution

  • if data[3] == 255

    The data has a length of 4 representing the RGBA. Where A alpha represents the opacity of the pixel. which has values from 0 to 255. 0 means completely transparent, and 255 means completely opaque. Here, I used data[3] > 200 to include those pixels too that have slight transparency.

    The code code changes to

    # import PIL module
    from PIL import Image
      
    img_da_maskerare = Image.open("temp.png")
    width = img_da_maskerare.size[0] 
    height = img_da_maskerare.size[1] 
    for i in range(0,width):
        for j in range(0,height):
            data = img_da_maskerare.getpixel((i,j))
    
            # RGBA = Red, Green, Blue, Alpha
            #  Alpha = 0 = transparent, 255 = opaque
            # alpha > 200 means almost opaque
            if data[3] >= 200:
                img_da_maskerare.putpixel((i,j),(00, 00, 00))
    
    img_da_maskerare.save('temp_maskerad.png')