Created
August 30, 2023 22:49
-
-
Save Lana-chan/5b4604c8a03b21a897161afa01bd3542 to your computer and use it in GitHub Desktop.
fix bad nearest-neighbor scaling and re-scale back up
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
""" | |
* ---------------------------------------------------------------------------- | |
* "THE BEER-WARE LICENSE" (Revision 42 modified): | |
* <[email protected]> wrote this file. As long as you retain this notice and | |
* my credit somewhere you can do whatever you want with this stuff. If we | |
* meet some day, and you think this stuff is worth it, you can buy me a beer | |
* in return. | |
* ---------------------------------------------------------------------------- | |
""" | |
from PIL import Image | |
import sys | |
THRESHOLD = 3 | |
RESCALE_FACTOR = 2 | |
if __name__ == "__main__": | |
if len(sys.argv) < 2: | |
print("drag and drop a file into me (or pass filename into commandline, optional second argument for output name)") | |
sys.exit() | |
filename, ext = sys.argv[1].split('.') | |
if len(sys.argv) < 3: | |
out_filename = f"{filename}-fixed" | |
else: | |
out_filename = sys.argv[2] | |
# lazy dumb programming mess | |
with Image.open(f"{filename}.{ext}") as im: | |
px = im.load() | |
width, height = im.size | |
newwidth, newheight = width, height | |
out = Image.new(im.mode, (width, height)) | |
px_out = out.load() | |
similar = 0 | |
last = [] | |
trueN = 0 | |
for x in range(width): | |
col = [px[x, i] for i in range(height)] | |
if col != last: | |
for y in range(height): | |
px_out[trueN, y] = col[y] | |
trueN += 1 | |
else: | |
similar += 1 | |
if similar > THRESHOLD: | |
similar = 0 | |
last = [] | |
last = col | |
newwidth = trueN | |
fix1 = out.copy() | |
px = fix1.load() | |
last = [] | |
trueN = 0 | |
for y in range(height): | |
row = [px[i, y] for i in range(width)] | |
if row != last: | |
for x in range(width): | |
px_out[x, trueN] = row[x] | |
trueN += 1 | |
else: | |
similar += 1 | |
if similar > THRESHOLD: | |
similar = 0 | |
last = [] | |
last = row | |
newheight = trueN | |
out = out.crop((0, 0, newwidth, newheight)) | |
out = out.resize((newwidth * RESCALE_FACTOR, newheight * RESCALE_FACTOR), Image.Resampling.NEAREST) | |
out.save(f"{out_filename}.{ext}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment