def build(paths, image_graph, sections=3): """Save representative data to json files in meta pack""" if not os.path.exists(paths.template_metadata): os.makedirs(paths.template_metadata) template_data = {} for json_filename in os.listdir(paths.template_metadata): with open(paths.template_metadata + json_filename, 'r') as json_file: json_data = json.load(json_file) template_data[json_data['group_name']] = json_data # Retrieve the relevant info for every texture keys = {} for bunch in [i for i in connected_components(image_graph) if len(i) > 1]: for node in bunch: Raster.from_path(paths.default_patches + node, 'RGBA') keys[node] = image_graph.node[node]['group_name'], Raster.from_path(paths.default_patches + node, 'RGBA') # Iterate through each file that is part of the key for key, (template_name, default_image) in keys.items(): # Load corresponding cluster map try: with open(paths.template_metadata + "\\" + os.path.split(template_name)[1] + ".json", 'r') as config: layer_map = ast.literal_eval(json.load(config)['cluster_map']) except FileNotFoundError: print("Could not find: " + paths.template_metadata + "\\" + os.path.split(template_name)[1] + ".json") continue # Use corresponding cluster map to break image into pieces try: image_clusters = filter_raster.layer_decomposite(default_image, layer_map) except ValueError: continue templ_clusters = filter_raster.layer_decomposite( Raster.from_path(paths.default_patches + template_name, 'RGBA'), layer_map) # Analyze each cluster segment_metalist = [] for ident, (segment, template_segment) in enumerate(zip(image_clusters, templ_clusters)): segment_data = analyze_image(segment, template_segment, sections) segment_data['id'] = ident segment_metalist.append(segment_data) meta_dict = { 'group_name': template_name, 'segment_dicts': segment_metalist } output_path = os.path.split(paths.file_metadata + key)[0] # Create folder structure if not os.path.exists(output_path): os.makedirs(output_path) # Save json file with open(output_path + "\\" + os.path.split(key)[1] + ".json", 'w') as output_file: json.dump(meta_dict, output_file, sort_keys=True, indent=2)
def make_template(template_name, template_directory, home): template_image = Raster.from_path(template_name, 'RGBA') image_clusters, guide = spectral_cluster(template_image) sections = len(image_clusters) print('-S: ' + str(len(image_clusters)) + ' | ' + template_name) # Analyze each cluster, save to list of dicts segment_metalist = [] for ident, segment in enumerate(image_clusters): cluster_data = analyze_image(segment, granularity=sections) cluster_data['id'] = ident segment_metalist.append(cluster_data) meta_dict = { 'group_name': template_name.replace(home, ''), 'segment_dicts': segment_metalist, 'cluster_map': json.dumps(guide.tolist()), 'shape': str(template_image.shape) } # Create folder structure if not os.path.exists(template_directory): os.makedirs(template_directory) # Save json file with open(template_directory + "\\" + os.path.split(template_name)[1] + ".json", 'w') as output_file: json.dump(meta_dict, output_file, sort_keys=True, indent=2)
def make_stencil(stencil_name, quantity, stencil_staging, stencil_configs, colorize, relative_path): masks = [] for id in range(quantity): stencil_path = os.path.normpath(stencil_staging + "\\" + stencil_name + "_" + str(id+1) + ".png") stencil = Raster.from_path(stencil_path, 'RGBA') masks.append(stencil.mask.tolist()) stencil_path = stencil_staging + "\\" + stencil_name + "_1.png" stencil_data = dict(name=stencil_name, shape=Raster.from_path(stencil_path, 'RGBA').shape.tolist(), mask=masks, colorize=colorize, path=relative_path) with open(stencil_configs + '//' + stencil_name + ".json", 'w') as output_file: json.dump(stencil_data, output_file, sort_keys=True)
def apply_stencil(data, paths, resourcepack): mapping_path, json_data = data image_components = [] for cluster_data in json_data['segment_dicts']: segment = Raster.from_path( paths.resource_skeletons + '//' + resourcepack + '//' + json_data['group_name'] + '_' + str(cluster_data['id']+1) + '.png', "RGBA") if not cluster_data['colorize']: image_components.append(segment) continue # Adjust contrast contrast_mult = abs(analyze.variance(segment, 'V') - math.sqrt(cluster_data['variance'])) * .1 segment = filters.contrast(segment, contrast_mult) # Adjust coloration layer_count = len(cluster_data['hues']) components = filters.value_decomposite(segment, layer_count) colorized_components = [] for i, layer in enumerate(components): sat_multiplier = 1-i/layer_count * 0.5 layer = filters.colorize(layer, cluster_data['hues'][i], cluster_data['sats'][i] * sat_multiplier, 0, 1, 1, 0) colorized_components.append(layer) staged_image = filters.composite(colorized_components) # Adjust lightness lightness_adjustment = cluster_data['lightness'] - analyze.mean(segment, 'V') staged_image = filters.brightness(staged_image, lightness_adjustment) image_components.append(staged_image) for component in image_components: component.to_rgb() output_image = filters.composite(image_components) # Output/save image full_path_output = str(mapping_path)\ .replace(paths.mappings_metadata_custom, paths.output_path + '//' + resourcepack + '//')\ .replace('.json', '') print('Generated: ' + mapping_path.replace(paths.mappings_metadata_custom, resourcepack + '//').replace('.json', '')) if not os.path.exists(os.path.split(full_path_output)[0]): os.makedirs(os.path.split(full_path_output)[0]) if os.path.exists(full_path_output): os.remove(full_path_output) output_image.save(full_path_output)
def image_masker(self): raster_layers = [] for i, stencilpath in enumerate(self.stencilpaths): image = Image.open(stencilpath) dim = min(image.size) image = image.crop((0, 0, dim, dim)) layer = Raster.from_image(image, "RGBA") if self.colorize[i]: layer = colorize(layer, self.hues[i], 1, .5, 1, .7, .5) raster_layers.append(layer) return composite(raster_layers).get_image().resize((400, 400), Image.NEAREST)
def load_stencil(self): stencil_data = json.load(open(os.path.normpath(self.stencildir + "\\" + self.stencilname + ".json"))) masks = stencil_data['mask'] self.layer_quantity = len(masks) self.relative_path = stencil_data['path'] self.imagestencil = Image.open(self.default_patches + '\\' + self.relative_path) self.stencilname = stencil_data['name'] self.master.title("Editing stencil: " + self.stencilname) self.colorize = stencil_data['colorize'] self.stencilpaths.clear() for index, mask in enumerate(masks): layer = Raster.from_image(self.imagestencil) layer.mask = np.array(mask) stencilpath = self.stenciledit + '\\' + self.stencilname + '_' + str(index+1) + '.png' layer.save(stencilpath) self.stencilpaths.append(stencilpath)
def build(paths, image_graph): """Generate template json files with spectral cluster maps""" template_listing = [] for bunch in connected_components(image_graph): bunch = connectivity_sort(bunch, image_graph)[0] first_image = Raster.from_path(paths.default_patches + bunch, 'RGBA') if first_image.shape != (16, 16): # TODO: Perfect place to tie in GUI generator continue try: template_listing.append(paths.default_patches + image_graph.node[bunch]['group_name']) except KeyError: continue vectorize(template_listing, make_template, (paths.template_metadata, paths.default_patches))
def click_stencil_select(self, event): if self.Frame3.curselection()[0] == 0: return stencil_name = self.Frame3.get(self.Frame3.curselection()[0]) stencil_data = json.load(open(os.path.normpath(self.settings.stencil_metadata + "\\" + stencil_name + ".json"))) masks = stencil_data['mask'] for selection in self.Listbox.curselection(): relative_path = self.Listbox.get(selection) image = Raster.from_image(Image.open( self.settings.default_patches + '//' + relative_path).resize(stencil_data['shape'], Image.NEAREST), "RGBA") segment_metalist = [] for ident, mask in enumerate(masks): if stencil_data['colorize'][ident]: image.mask = mask segment_data = analyze_image(image) segment_data['id'] = ident segment_data['colorize'] = True segment_metalist.append(segment_data) else: segment_data = {} segment_data['id'] = ident segment_data['colorize'] = False segment_metalist.append(segment_data) meta_dict = { 'group_name': stencil_name, 'segment_dicts': segment_metalist } output_path = os.path.split(self.settings.mappings_metadata_custom + relative_path)[0] # Create folder structure if not os.path.exists(output_path): os.makedirs(output_path) # Save json file with open(output_path + "\\" + os.path.basename(relative_path) + ".json", 'w') as output_file: json.dump(meta_dict, output_file, sort_keys=True, indent=2) self.click_search_item(None)
def image_hash(full_path, target, raster_lock, raster_dict): def threshold(array_in, thresh=0.5): array_mask = array_in.copy() array_mask[array_mask > thresh] = 1.0 array_mask[array_mask <= thresh] = 0.0 return array_mask try: image_path = full_path.replace(target, "") candidate = Raster.from_path(full_path, 'RGBA') image_hash_id = ''.join(char for char in np.array_str(threshold(candidate.mask)) if char.isdigit()) # Categorize images by thresholded layer mask with raster_lock: listobj = raster_dict[image_hash_id] listobj.append(image_path) raster_dict[image_hash_id] = listobj except OSError: pass
def click_resourcepack(self, event): selection = self.ResourcepackListing.curselection() if selection[0] == 0: if not os.path.exists(self.settings.resource_skeletons + 'New_Resourcepack'): os.makedirs(self.settings.resource_skeletons + 'New_Resourcepack') resourcepack_folder = 'New_Resourcepack' else: resourcepack_folder = self.ResourcepackListing.get(selection[0]) for stencil in os.listdir(self.settings.stencil_metadata): stencil_data = json.load(open(self.settings.stencil_metadata + '\\' + stencil)) masks = stencil_data['mask'] for ident, mask in enumerate(masks): path = self.settings.resource_skeletons + \ resourcepack_folder + '\\' + stencil.replace('.json', '') + '_' + str(ident+1) + '.png' if os.path.exists(path): continue layer = Raster.from_path(self.settings.default_patches + '\\' + stencil_data['path'], "RGBA") layer.mask = mask layer.save(path)
from Raster.Raster import Raster import numpy as np image = Raster.from_path(r"C:\Users\mike_000\Desktop\images.png", "RGBA") image_edited = Raster.from_array(np.rot90(image.get_tiered()), "RGBA") shape = image.get_tiered().shape[:2] print(shape) coords = np.zeros(shape + (2,)) for indice_x in range(shape[0]): for indice_y in range(shape[1]): coords[indice_x, indice_y, 0] = indice_x coords[indice_x, indice_y, 1] = indice_y x_transposed = coords[:,:,0].T y_transposed = coords[:,:,1].T image_rotated = np.zeros(tuple(reversed(shape)) + (4,)) print(image_rotated.shape) for indice_x in range(shape[1]): for indice_y in range(shape[0]): image_rotated[indice_x, indice_y] = image.get_tiered()[x_transposed[indice_x,indice_y], y_transposed[indice_x, indice_y]] print(image_rotated) Raster.from_array(image_rotated, "RGBA").save(r"C:\Users\mike_000\Desktop\image_rotated.png")
def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) self.setFixedSize(self.size()) self.fit = None """ :type: Module.Abstrakt.Fit.Fit """ self.gui_raster_laden = GuiRasterLaden(self) self.gui_spektr_laden = GuiSpektrLaden(self) # TODO nicht mehr nötig: self.plots = [] # Die Plots werden durch ihren Konstruktor automatisch dieser Liste hinzugefügt # Raster-Plots self.plt_raster_resonanzkurve = RasterResonanz( gui=self, titel=gui_resonanzkurve[lang], beschriftung=Achsenbeschriftung(x=achse_freq[lang], y=achse_amp[lang]) ) self.plt_raster_phase_schnitt = Schnitt( gui=self, titel=gui_phase_schnitt[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_phase[lang]) ) self.plt_raster_amp_schnitt = Schnitt( gui=self, titel=gui_amp_schnitt[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_amp[lang]) ) self.plt_raster_freq_schnitt = Schnitt( gui=self, titel=gui_freq_schnitt[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_freq[lang]) ) self.plt_raster_phase = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_phase[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang], farbe=achse_phase[lang]) ) self.plt_raster_resfreq = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_resfreq[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang], farbe=achse_freq[lang]) ) self.plt_raster_amplitude = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_amplitude[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang], farbe=achse_amp[lang]) ) self.plt_raster_qfaktor = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_qfaktor[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang]) ) # Spektroskopie-Plots self.plt_spektr_resonanzkurve = SpektrResonanz( gui=self, titel=gui_resonanzkurve[lang], beschriftung=Achsenbeschriftung(x=achse_freq[lang], y=achse_amp[lang]) ) self.action_raster.triggered.connect(self.raster_laden) self.action_spektroskopie.triggered.connect(self.spektr_laden) self.action_speichern.triggered.connect(self.speichern) self.action_resonanzkurve.triggered.connect(self.plt_raster_resonanzkurve.zeige) self.action_phase_schnitt.triggered.connect(self.plt_raster_phase_schnitt.zeige) self.action_amp_schnitt.triggered.connect(self.plt_raster_amp_schnitt.zeige) self.action_resfreq.triggered.connect(self.plt_raster_resfreq.zeige) self.action_amplitude.triggered.connect(self.plt_raster_amplitude.zeige) self.action_phase.triggered.connect(self.plt_raster_phase.zeige) self.action_qfaktor.triggered.connect(self.plt_raster_qfaktor.zeige) self.action_alles.triggered.connect(self.zeige_alles) self.action_aktualisieren.triggered.connect(self.aktualisieren) self.action_anregung.triggered.connect(self.plt_spektr_resonanzkurve.zeige) # TODO: self.action_spektr_amp.setEnabled(False) self.action_spektr_freq.setEnabled(False) self.action_spektr_phase.setEnabled(False)
class Gui(QtGui.QMainWindow, Ui_Gui): """ Menüfenster mit Rohdatenanzeige """ def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) self.setFixedSize(self.size()) self.fit = None """ :type: Module.Abstrakt.Fit.Fit """ self.gui_raster_laden = GuiRasterLaden(self) self.gui_spektr_laden = GuiSpektrLaden(self) # TODO nicht mehr nötig: self.plots = [] # Die Plots werden durch ihren Konstruktor automatisch dieser Liste hinzugefügt # Raster-Plots self.plt_raster_resonanzkurve = RasterResonanz( gui=self, titel=gui_resonanzkurve[lang], beschriftung=Achsenbeschriftung(x=achse_freq[lang], y=achse_amp[lang]) ) self.plt_raster_phase_schnitt = Schnitt( gui=self, titel=gui_phase_schnitt[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_phase[lang]) ) self.plt_raster_amp_schnitt = Schnitt( gui=self, titel=gui_amp_schnitt[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_amp[lang]) ) self.plt_raster_freq_schnitt = Schnitt( gui=self, titel=gui_freq_schnitt[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_freq[lang]) ) self.plt_raster_phase = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_phase[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang], farbe=achse_phase[lang]) ) self.plt_raster_resfreq = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_resfreq[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang], farbe=achse_freq[lang]) ) self.plt_raster_amplitude = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_amplitude[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang], farbe=achse_amp[lang]) ) self.plt_raster_qfaktor = Raster( gui=self, resonanzkurve=self.plt_raster_resonanzkurve, titel=gui_qfaktor[lang], beschriftung=Achsenbeschriftung(x=achse_punkt_x[lang], y=achse_punkt_y[lang]) ) # Spektroskopie-Plots self.plt_spektr_resonanzkurve = SpektrResonanz( gui=self, titel=gui_resonanzkurve[lang], beschriftung=Achsenbeschriftung(x=achse_freq[lang], y=achse_amp[lang]) ) self.action_raster.triggered.connect(self.raster_laden) self.action_spektroskopie.triggered.connect(self.spektr_laden) self.action_speichern.triggered.connect(self.speichern) self.action_resonanzkurve.triggered.connect(self.plt_raster_resonanzkurve.zeige) self.action_phase_schnitt.triggered.connect(self.plt_raster_phase_schnitt.zeige) self.action_amp_schnitt.triggered.connect(self.plt_raster_amp_schnitt.zeige) self.action_resfreq.triggered.connect(self.plt_raster_resfreq.zeige) self.action_amplitude.triggered.connect(self.plt_raster_amplitude.zeige) self.action_phase.triggered.connect(self.plt_raster_phase.zeige) self.action_qfaktor.triggered.connect(self.plt_raster_qfaktor.zeige) self.action_alles.triggered.connect(self.zeige_alles) self.action_aktualisieren.triggered.connect(self.aktualisieren) self.action_anregung.triggered.connect(self.plt_spektr_resonanzkurve.zeige) # TODO: self.action_spektr_amp.setEnabled(False) self.action_spektr_freq.setEnabled(False) self.action_spektr_phase.setEnabled(False) def retranslateUi(self, ui): """ :type ui: QtGui.QMainWindow """ ui.setWindowTitle(gui_titel[lang]) self.label_amplitude.setText(gui_amplitude[lang]) self.label_phase.setText(gui_phase[lang]) self.menu_auswertung.setTitle(gui_auswertung[lang]) self.menu_raster.setTitle(gui_raster[lang]) self.menu_spektroskopie.setTitle(gui_spektroskopie[lang]) self.action_spektroskopie.setText(gui_lade_spektroskopie[lang]) self.action_messparameter.setText(gui_messparameter[lang]) self.action_raster.setText(gui_lade_raster[lang]) self.action_speichern.setText(gui_speichern[lang]) self.action_resonanzkurve.setText(gui_resonanzkurve[lang]) self.action_phase_schnitt.setText(gui_phase_schnitt[lang]) self.action_amp_schnitt.setText(gui_amp_schnitt[lang]) self.action_resfreq.setText(gui_resfreq[lang]) self.action_amplitude.setText(gui_amplitude[lang]) self.action_phase.setText(gui_phase[lang]) self.action_qfaktor.setText(gui_qfaktor[lang]) self.action_alles.setText(gui_alles[lang]) self.action_anregung.setText(gui_anregung[lang]) self.action_spektr_amp.setText(gui_amplitude[lang]) self.action_spektr_freq.setText(gui_resfreq[lang]) self.action_spektr_phase.setText(gui_phase[lang]) def closeEvent(self, event): """ :type event: PyQt4.QtCore.QEvent """ sys.exit(0) def importiert(self): # Name der Messung anzeigen self.label_name.setText(os.path.basename(self.fit.par.verzeichnis)) # Dateiliste befüllen def model(namen): item_model = QtGui.QStandardItemModel() for name in namen: item_model.appendRow(QtGui.QStandardItem(name)) return item_model self.list_amplitude.setModel(model(self.fit.messwerte.amplitude_namen)) self.list_phase.setModel(model(self.fit.messwerte.phase_namen)) # Resonanzplots bereitstellen if self.fit.__class__ == RasterFit: self.plt_raster_resonanzkurve.set_werte(self.fit.messwerte.amplitude) self.menu_raster.setEnabled(True) self.menu_spektroskopie.setEnabled(False) else: self.plt_spektr_resonanzkurve.set_werte(self.fit.messwerte) self.menu_raster.setEnabled(False) self.menu_spektroskopie.setEnabled(True) def raster_laden(self): self.gui_raster_laden.show() self.gui_raster_laden.raise_() def spektr_laden(self): self.gui_spektr_laden.show() self.gui_spektr_laden.raise_() def speichern(self): wohin = QtGui.QFileDialog().getSaveFileName(self, rf_ordner[lang], self.fit.par.verzeichnis) self.fit.speichern(str(wohin)) hinweis(self, gui_gespeichert[lang] + wohin) def raster_fit_fertig(self): self.action_speichern.setEnabled(True) self.menu_raster.setEnabled(True) erg = self.fit.erg """ :type: Module.Raster.Ergebnis.Ergebnis """ self.plt_raster_phase_schnitt.set_werte(erg.phase) self.plt_raster_amp_schnitt.set_werte(erg.amp) self.plt_raster_freq_schnitt.set_werte(erg.resfreq) self.plt_raster_phase.set_werte(erg.phase) self.plt_raster_resfreq.set_werte(erg.resfreq) self.plt_raster_amplitude.set_werte(erg.amp) self.plt_raster_qfaktor.set_werte(erg.q) def spektr_fit_fertig(self): self.action_speichern.setEnabled(True) self.menu_spektroskopie.setEnabled(True) print('TODO: Fit fertig, restliche Plots bereitstellen') """import matplotlib.pyplot as plt ac = self.fit.messwerte.omega(1).ac(7.) dc = ac.dc.index(-4.) plt.plot( self.fit.messwerte.frequenzen, ac.amp_freq[dc], antialiased=True ) dc = ac.dc.index(-4.025) plt.plot( self.fit.messwerte.frequenzen, ac.amp_freq[dc], antialiased=True ) plt.show()""" def aktualisieren(self): for plt in self.plots: plt.aktualisieren() def zeige_alles(self): for plt in self.plots: # TODO stattdessen alle Graphen in einem Fenster darstellen plt.zeige()