content/encode.py

78 lines
2.0 KiB
Python

import cv2
from argparse import ArgumentParser
import json
from common import convert_color, closest_color, create_colored_image, remove_from_list, closest_color_euclidean, closest_color_weighted_euclidean, euclidean_distance, weighted_euclidean_distance
parser = ArgumentParser()
parser.add_argument('input', help='Input image')
parser.add_argument('output', help='Output bin')
args = parser.parse_args()
with open('palette16.json', 'r') as file:
palette16 = json.load(file)
with open('palettegray.json', 'r') as file:
palettegray = json.load(file)
def find_array_index(arrays, target):
return next((i for i, arr in enumerate(arrays) if arr == target), -1)
palette = []
for a in range(16) :
for b in range(16) :
palette.append([ a, b ])
#print(palette)
#exit()
file_path = args.output
img = cv2.imread(args.input, cv2.COLOR_BGR2RGB) #, cv2.IMREAD_GRAYSCALE)
height, width, depth = img.shape
def compare (p) :
score = 0
pair = [0, 0]
vals = []
for i in range(height):
for j in range(width):
k = img[i, j]
closest, dist = closest_color_weighted_euclidean(p, k, 'RGB')
score += dist
#print(closest)
index = find_array_index(p, closest)
if len(pair) == 2 :
b = find_array_index(palette, pair)
if b == -1 :
print(f'{pair}')
vals.append(b)
pair = []
if len(pair) < 2 :
pair.append(index)
if len(pair) == 1 :
pair.append(0)
if len(pair) == 2 :
vals.append(find_array_index(palette, pair))
return score, vals
score16, vals16 = compare(palette16['palette'])
scoregray, valsgray = compare(palettegray['palette'])
print(f'{scoregray} vs. {score16 / 3}')
if scoregray < (score16 / 3) :
vals = valsgray
vals[0] = 0
print('B&W')
else :
vals = vals16
vals[0] = 1
print('Color')
print(f'{len(vals)} bytes')
with open(file_path, "wb") as file:
file.write(bytes(vals))