Пример #1
0
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)
Пример #2
0
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)
Пример #3
0
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)
Пример #4
0
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)
Пример #5
0
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))
Пример #6
0
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
Пример #7
0
    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)
Пример #8
0
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")