marker_separation/py/pallete_schema.py

78 lines
2.4 KiB
Python

from jsonschema import validate
from json import dumps, loads
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
class PalleteSchema :
colors = None
schema = {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"name" : { "type" : "string" },
"color" : {
"type" : "array",
"items" : { "type" : "number" }
},
"space" : { "type" : "string" }
},
"required" : [ "name", "color", "space" ]
}
}
def __init__ (self, file = None, obj = None):
if file is not None and obj is None:
self.parse_file(file)
elif file is not None and obj is not None :
self.write(file, obj)
else :
print('Not sure what you\'re trying to do here')
def parse_file (self, file) :
with open(file) as f :
self.parse(f.read())
print(f'Parsed pallete file {file}')
def parse (self, jsonstr) :
obj = loads(jsonstr)
validate( instance = obj, schema = self.schema)
self.colors = obj
def write(self, filepath, obj) :
validate( instance = obj, schema = self.schema)
jsonstr = dumps(obj, indent = 4)
with open(filepath, 'w') as outfile :
outfile.write(jsonstr)
def closest (self, comparison, space = 'BGR', colors = None) :
c = colors if colors is not None else self.colors
colors = normalize_colors(space, c)
if space == 'RGB' or space == 'BGR' :
closest, dist = closest_color_weighted_euclidean(colors, comparison, space)
else :
closest, dist = closest_color_euclidean(colors, comparison)
print(f'Color [{space}] {comparison} closest to {closest} [{dist}]')
return closest
def closest_exclusive (self, comparisons, space = 'BGR', colors = None) :
c = colors if colors is not None else self.colors
colors = normalize_colors(space, c)
exclusive = []
for comparison in comparisons :
if space == 'RGB' or space == 'BGR' :
closest, dist = closest_color_weighted_euclidean(colors, comparison, space)
else :
closest, dist = closest_color_euclidean(colors, comparision)
colors = remove_from_list(colors, closest)
exclusive.append(closest)
return exclusive
def normalize_colors (self, space = 'BGR', colors = None) :
normalized = []
c = colors if colors is not None else self.colors
for color in c :
normalized.append(convert_color(color['color'], color['space'], space))
return normalized