Created
September 16, 2023 19:49
-
-
Save mildsunrise/07000dbdcd568edbddeb406992ec5158 to your computer and use it in GitHub Desktop.
SIGNALIS save data decoder/encoder
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
#!/usr/bin/python | |
""" | |
signalis.py decode <input.png> <output.json> | |
signalis.py encode <input.json> <output.png> | |
the decoder does NOT validate the input image! to do that, encode data again and check image pixels match | |
""" | |
import os, sys | |
import numpy as np | |
from PIL import Image | |
def __main__(): | |
args = sys.argv[1:] | |
if len(args) != 3: | |
print(__doc__, file=sys.stderr) | |
exit(1) | |
mode, infile, outfile = args | |
{ "decode": decode, "encode": encode }[mode](infile, outfile) | |
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "template.png") | |
template = np.array(Image.open(TEMPLATE_PATH)) | |
def decode(infile: str, outfile: str): | |
image = np.array(Image.open(infile, "r", ["png"])) | |
data = (template != image)[::-1, :, :3].reshape(-1, 8) | |
data = bytes( sum(int(b[i]) << i for i in range(8)) for b in data ) | |
end = len(data) | |
while end and data[end - 1] == 0: end -= 1 | |
data = data[:end] | |
with open(outfile, "wb") as f: | |
f.write(data) | |
def encode(infile: str, outfile: str): | |
image = template.copy() | |
with open(infile, "rb") as f: | |
data = f.read() | |
pixels = image[::-1, :, :3] | |
values = pixels.reshape(-1) | |
write_values(values, data) | |
pixels[:] = values.reshape(pixels.shape) | |
Image.fromarray(image).save(outfile, "png") | |
def write_values(values: np.ndarray, data: bytes): | |
assert not data.endswith(b"\0") | |
bits = ( (byte >> i) & 1 for byte in data for i in range(8) ) | |
for i, bit in enumerate(bits): | |
diff = bit * 10 | |
if values[i] + diff > 255: | |
# adding would cause an overflow; subtract instead | |
diff *= -1 | |
values[i] += diff | |
if __name__ == "__main__": | |
__main__() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are a lifesaver, i cannot thank you enough.