Created
August 7, 2019 23:07
-
-
Save Ruffo324/5d4089d39671ccb3aeff149fa362069e to your computer and use it in GitHub Desktop.
JPEG to PNG with color replacement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
import os | |
print("JPEG to PNG converter with Color replacement started.") | |
sourceDirectory = ".\source_images" | |
targetDirectory = ".\converted_images" | |
minColorValue = 235 | |
maxColorValue = 255 | |
def processImage(filename): | |
print("Processing image '" + filename + "'...") | |
img = Image.open(os.path.join(sourceDirectory, filename)) | |
img = img.convert("RGBA") | |
datas = img.getdata() | |
newData = [] | |
for index, data in enumerate(datas): | |
replaceColor = True | |
for i in range(2): | |
replaceColor = replaceColor and minColorValue <= data[ | |
i] <= maxColorValue | |
if replaceColor: | |
if index - 1 >= 0 and index + 1 <= len(datas): | |
for nI in range(index - 1, index + 1): #nI = nearIndex | |
for i in range(2): | |
replaceColor &= minColorValue <= datas[nI][ | |
i] <= maxColorValue | |
if replaceColor: | |
newData.append((255, 255, 255, 0)) | |
else: | |
newData.append(data) | |
# Debug output | |
if index % 10000 == 0: | |
print(str(index) + "/" + str(len(datas))) | |
newFileName = os.path.splitext(os.path.join(targetDirectory, | |
filename))[0] + '.png' | |
img.putdata(newData) | |
img.save(newFileName, "PNG") | |
print("Done.") | |
# Iterate through files from source directory. | |
for filename in os.listdir(sourceDirectory): | |
if filename.endswith(".jpg") or filename.endswith(".jpeg"): | |
processImage(filename) | |
continue | |
else: | |
continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment