Skip to content

Instantly share code, notes, and snippets.

@skuralll
Last active May 16, 2022 14:12
Show Gist options
  • Save skuralll/f54c18cac0bc8f693bac38ac96f8c817 to your computer and use it in GitHub Desktop.
Save skuralll/f54c18cac0bc8f693bac38ac96f8c817 to your computer and use it in GitHub Desktop.
画像をアンミ化(白200色)するスクリプト
import catch as catch
from PIL import Image
import random
RGB_MIN = 230
RGB_MAX = 255
COLOR_NUM = 200
# open original image
while True:
try:
imagePath = input("Input image path:")
img = Image.open(imagePath)
except Exception as e:
print("Path is invalid")
else:
break
# generate 200 white colors
elementRange = range(RGB_MIN, RGB_MAX + 1)
whiteColors = [ # all white colors
[r, g, b]
for r in elementRange
for g in elementRange
for b in elementRange
]
random.shuffle(whiteColors)
colors = whiteColors[:COLOR_NUM]
# change colors
width, height = img.size
imgdata = img.getdata()
afterdata = [(0, 0, 0)] * (width * height)
for y in range(height):
for x in range(width):
originPixel = imgdata[y * width + x]
originColor = [originPixel[0], originPixel[1], originPixel[2]]
normalizedColor = list(map(lambda ele: int((ele/255) * (RGB_MAX - RGB_MIN) + RGB_MIN), originColor))
afterColor = (0, 0, 0)
mindif = 255 * 3
for color in colors: # get closest color
dif = abs(color[0] - normalizedColor[0]) + abs(color[1] - normalizedColor[1]) + abs(color[2] - normalizedColor[2])
if dif < mindif:
mindif = dif
afterColor = (color[0], color[1], color[2])
afterdata[y * width + x] = afterColor
img.putdata(afterdata)
img.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment