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
92
tools/rle_encode.py
Normal file → Executable file
92
tools/rle_encode.py
Normal file → Executable file
|
@ -1,51 +1,67 @@
|
||||||
|
#!/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 = []
|
||||||
rl = 0
|
rl = 0
|
||||||
px = 0
|
px = 0
|
||||||
|
|
||||||
for y in range(im.height):
|
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:
|
||||||
rl += 1
|
if rl < 255:
|
||||||
continue
|
rl += 1
|
||||||
assert(rl < 255)
|
else:
|
||||||
rle.append(rl)
|
# Handle overflow
|
||||||
rl = 1
|
rle.append(255)
|
||||||
px = newpx
|
rle.append(0)
|
||||||
rle.append(rl)
|
rl = 1
|
||||||
|
continue
|
||||||
|
|
||||||
sx = 240
|
# Start a new run
|
||||||
sy = 240
|
rle.append(rl)
|
||||||
image = bytes(rle)
|
rl = 1
|
||||||
|
px = newpx
|
||||||
|
# Handle the final run
|
||||||
|
rle.append(rl)
|
||||||
|
|
||||||
|
return (im.width, im.height, bytes(rle))
|
||||||
|
|
||||||
data = bytearray(2*sx)
|
def decode_to_ascii(image):
|
||||||
dp = 0
|
(sx, sy, rle) = image
|
||||||
black = ord('#')
|
data = bytearray(2*sx)
|
||||||
white = ord(' ')
|
dp = 0
|
||||||
color = black
|
black = ord('#')
|
||||||
|
white = ord(' ')
|
||||||
|
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
|
||||||
dp += 2
|
dp += 2
|
||||||
rl -= 1
|
rl -= 1
|
||||||
|
|
||||||
if dp >= (2*sx):
|
if dp >= (2*sx):
|
||||||
print(data.decode('utf-8'))
|
print(data.decode('utf-8'))
|
||||||
dp = 0
|
dp = 0
|
||||||
|
|
||||||
if color == black:
|
if color == black:
|
||||||
color = white
|
color = white
|
||||||
else:
|
else:
|
||||||
color = black
|
color = black
|
||||||
|
|
||||||
assert(dp == 0)
|
# Check the image is the correct length
|
||||||
|
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