marker_separation/py/pallete_schema.py

58 lines
1.6 KiB
Python
Raw Normal View History

from jsonschema import validate
from json import dumps, loads
2023-11-21 18:28:49 +00:00
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 :
2023-11-21 18:28:49 +00:00
outfile.write(jsonstr)
def closest (self, comparison, space = 'BGR', pallete = None) :
p = pallete if pallete is not None else self.pallete
colors = normalize_colors(space, )
def normalize_colors (self, space = 'BGR', pallete = None) :
colors = []
for color in pallete :
colors.append(convert_color(color['color'], color['space'], space))
return colors