tools: rle_encode: Rework into proper functions
This commit is contained in:
parent
8f231430b3
commit
4604603352
1 changed files with 55 additions and 39 deletions
30
tools/rle_encode.py
Normal file → Executable file
30
tools/rle_encode.py
Normal file → Executable file
|
@ -1,6 +1,9 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import sys
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
im = Image.open('pine64.png')
|
def encode(im):
|
||||||
pixels = im.load()
|
pixels = im.load()
|
||||||
|
|
||||||
rle = []
|
rle = []
|
||||||
|
@ -11,26 +14,33 @@ for y in range(im.height):
|
||||||
for x in range(im.width):
|
for x in range(im.width):
|
||||||
newpx = pixels[x, y]
|
newpx = pixels[x, y]
|
||||||
if newpx == px:
|
if newpx == px:
|
||||||
|
if rl < 255:
|
||||||
rl += 1
|
rl += 1
|
||||||
|
else:
|
||||||
|
# Handle overflow
|
||||||
|
rle.append(255)
|
||||||
|
rle.append(0)
|
||||||
|
rl = 1
|
||||||
continue
|
continue
|
||||||
assert(rl < 255)
|
|
||||||
|
# Start a new run
|
||||||
rle.append(rl)
|
rle.append(rl)
|
||||||
rl = 1
|
rl = 1
|
||||||
px = newpx
|
px = newpx
|
||||||
|
# Handle the final run
|
||||||
rle.append(rl)
|
rle.append(rl)
|
||||||
|
|
||||||
sx = 240
|
return (im.width, im.height, bytes(rle))
|
||||||
sy = 240
|
|
||||||
image = bytes(rle)
|
|
||||||
|
|
||||||
|
|
||||||
|
def decode_to_ascii(image):
|
||||||
|
(sx, sy, rle) = image
|
||||||
data = bytearray(2*sx)
|
data = bytearray(2*sx)
|
||||||
dp = 0
|
dp = 0
|
||||||
black = ord('#')
|
black = ord('#')
|
||||||
white = ord(' ')
|
white = ord(' ')
|
||||||
color = black
|
color = black
|
||||||
|
|
||||||
for rl in image:
|
for rl in rle:
|
||||||
while rl:
|
while rl:
|
||||||
data[dp] = color
|
data[dp] = color
|
||||||
data[dp+1] = color
|
data[dp+1] = color
|
||||||
|
@ -46,6 +56,12 @@ for rl in image:
|
||||||
else:
|
else:
|
||||||
color = black
|
color = black
|
||||||
|
|
||||||
|
# Check the image is the correct length
|
||||||
assert(dp == 0)
|
assert(dp == 0)
|
||||||
|
|
||||||
|
image = encode(Image.open(sys.argv[1]))
|
||||||
|
# This is kinda cool for testing but let's leave this disabled until we add
|
||||||
|
# proper argument processing!
|
||||||
|
#decode_to_ascii(image)
|
||||||
|
print(f'# 1-bit RLE, generated from {sys.argv[1]}')
|
||||||
print(image)
|
print(image)
|
||||||
|
|
Loading…
Reference in a new issue