Page MenuHomeWildfire Games
Paste P243

Script to replace B&W background in transparent pixels on PNG textures
ActivePublic

Authored by vladislavbelov on Feb 12 2021, 9:43 AM.
import os
import sys
from PIL import Image, ImageDraw
def distance(color1, color2):
dist = 0
for component in range(3):
delta = abs(color1[component] - color2[component])
dist += delta ** 2
return dist
def convert_transparent(path):
print(path)
image = Image.open(path)
if image.mode != 'RGBA':
return
data = image.getdata()
number_of_wb = 0
number_of_a = 0
total_color = [0, 0, 0]
total_weight = 0
for y in range(image.size[1]):
for x in range(image.size[0]):
color = image.getpixel((x, y))
weight = color[3]
total_weight += weight
if weight > 0:
for component in range(3):
total_color[component] += color[component] * weight
if distance(color, (0, 0, 0)) < 75 or distance(color, (255, 255, 255)) < 75:
number_of_wb += 1
if color[3] == 0:
number_of_a += 1
if number_of_wb < number_of_a - number_of_a / 10:
return
avg_color = [0, 0, 0]
for component in range(3):
avg_color[component] = total_color[component] / total_weight
rem = total_color[component] % total_weight
if rem > total_weight / 2:
avg_color[component] += 1
if avg_color[component] < 0:
avg_color[component] = 0
elif avg_color[component] > 255:
avg_color[component] = 255
for y in range(image.size[1]):
for x in range(image.size[0]):
color = list(image.getpixel((x, y)))
if color[3] <= 1:
for component in range(3):
color[component] = int(avg_color[component])
image.putpixel((x, y), tuple(color))
image.save(path)
def convert_recursively(path):
for file_name in os.listdir(path):
file_path = os.path.join(path, file_name)
if os.path.isfile(file_path):
name, ext = os.path.splitext(file_name)
if ext.lower() in ['.png']:
convert_transparent(file_path)
elif os.path.isdir(file_path):
convert_recursively(file_path)
if __name__ == '__main__':
paths = sys.argv[1:]
for path in paths:
if os.path.isfile(path):
convert_transparent(path)
elif os.path.isdir(path):
convert_recursively(path)

Event Timeline

Stan changed the visibility from "All Users" to "Public (No Login Required)".