Reputation: 919
I have a large set of images. Some are JPEG, some are PNG. For the PNGs, I am making a program to convert all transparent pixels into plain white. However, not only does it not work, some of the backgrounds change to random colors such as red and green. I have no idea what I'm doing wrong, so here is my code:
import os
from PIL import Image
files = os.listdir("/Users/Riley/PycharmProjects/myNN/logos")
for file in files:
print(file)
image = Image.open("/Users/Riley/PycharmProjects/myNN/logos/" + file)
pixels = image.load()
if image.mode == 'RGBA':
print("RGBA")
for x in range(image.size[0]):
for y in range(image.size[1]):
if pixels[x, y][3] < 1:
pixels[x, y] == (255, 255, 255, 1)
print(pixels[x, y])
image = image.convert('RGB')
The print(pixels[x, y])
is for troubleshooting. I get no error, yet it prints out random RGBA values despite just then setting it to (255, 255, 255, 1).
Thanks.
Upvotes: 0
Views: 258
Reputation: 207425
You don't need to do that. It is easier and faster to make a new image in white the same size as your one with transparency and paste the one with transparency on top and the white will show through.
from PIL import Image
# Open original with transparency
im = Image.open('image.png').convert('RGBA')
# Make white background same size
white = Image.new('RGB',im.size,color='white')
# Paste onto background
white.paste(im,mask=im)
# Save
white.save('result.png')
By the way, you can do that without writing any Python at all, just using ImageMagick which is installed on most Linux distros and is available for macOS and Windows.
First, make an output directory where results will go:
mkdir output
Then flatten all your PNGs in one go onto white backgrounds:
magick mogrify -path output -background white -flatten /Users/Riley/PycharmProjects/myNN/logos/*png
If your ImageMagick is v6 or older, drop the magick
and use:
mkdir output
mogrify -path output -background white -flatten /Users/Riley/PycharmProjects/myNN/logos/*png
Upvotes: 2
Reputation: 60474
pixels[x, y] == (255, 255, 255, 1)
is a comparison, not an assignment.
You might want to replace that statement with pixels[x, y] = (255, 255, 255, 1)
.
Upvotes: 1