Skip to content

Commit

Permalink
Have palfix.py always output grayscale
Browse files Browse the repository at this point in the history
Fixes #431
  • Loading branch information
Rangi42 committed Nov 21, 2023
1 parent 77887be commit e8868d5
Showing 1 changed file with 5 additions and 19 deletions.
24 changes: 5 additions & 19 deletions tools/palfix.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
"""
Usage: python palfix.py image.png
Fix the palette format of the input image. Colored images (Gen 2 Pokémon or
trainer sprites) will become indexed, with a palette sorted {white, light
color, dark color, black}. Grayscale images (all Gen 1 images) will become
two-bit grayscale.
Fix the palette format of the input image to two-bit grayscale.
Colored images will have their palette sorted {white, light
color, dark color, black}.
"""

import sys
Expand All @@ -18,10 +17,6 @@ def rgb8_to_rgb5(c):
r, g, b = c
return (r // 8, g // 8, b // 8)

def rgb5_to_rgb8(c):
r, g, b = c
return (r * 8 + r // 4, g * 8 + g // 4, b * 8 + b // 4)

def invert(c):
r, g, b = c
return (31 - r, 31 - g, 31 - b)
Expand All @@ -33,10 +28,6 @@ def luminance(c):
def rgb5_pixels(row):
yield from (rgb8_to_rgb5(row[x:x+3]) for x in range(0, len(row), 4))

def is_grayscale(palette):
return (palette == ((31, 31, 31), (21, 21, 21), (10, 10, 10), (0, 0, 0)) or
palette == ((31, 31, 31), (20, 20, 20), (10, 10, 10), (0, 0, 0)))

def fix_pal(filename):
with open(filename, 'rb') as file:
width, height, rows = png.Reader(file).asRGBA8()[:3]
Expand All @@ -52,13 +43,8 @@ def fix_pal(filename):
return False
palette = tuple(sorted(colors | b_and_w, key=luminance, reverse=True))
assert len(palette) == 4
rows = [list(map(palette.index, rgb5_pixels(row))) for row in rows]
if is_grayscale(palette):
rows = [[3 - c for c in row] for row in rows]
writer = png.Writer(width, height, greyscale=True, bitdepth=2, compression=9)
else:
palette = tuple(map(rgb5_to_rgb8, palette))
writer = png.Writer(width, height, palette=palette, bitdepth=8, compression=9)
rows = [[3 - palette.index(c) for c in rgb5_pixels(row)] for row in rows]
writer = png.Writer(width, height, greyscale=True, bitdepth=2, compression=9)
with open(filename, 'wb') as file:
writer.write(file, rows)
return True
Expand Down

0 comments on commit e8868d5

Please sign in to comment.