示例#1
0
def bfs_preprocess(image_path,
                   new_size,
                   number_of_colors,
                   t1,
                   t2,
                   number_of_cc,
                   graph_type,
                   reversed_colors=True):
    '''
	This is the combination of pre_extraction_from_image and tree_approximation.
	:param image_path: string.
	:param number_of_colors: number of colors for the output image.
	:param t1: noise threshold. If t=0, then all the new pixels are preserved with their new colors.
	:param t2: threshold for the weights of the edges after pre-extraction.
	:param number_of_cc: number of connected components of the graph represented by the image. If None, then only 1
	cc is assumed.
	:param graph_type: 1 (to use edges and vertices of the grid), 2 (to use only edges).
	:return:
		bfs_Graph: bfs approximation of G.
	'''

    print('bfs_preprocessing...')

    width, color_dict, folder_path = resizing_image(image_path,
                                                    number_of_colors, new_size,
                                                    t1, reversed_colors)

    Graph, _ = pre_extraction_from_image(image_path, new_size, t2,
                                         number_of_colors, number_of_cc,
                                         graph_type, t1, reversed_colors)

    bfs_Graph = tree_approximation(Graph)

    partition_dict, _, _ = quality_measure.partition_set(width + 1)

    with open(folder_path + '/bfs_extracted_graph.pkl', 'wb') as file:
        pkl.dump(bfs_Graph, file)

    with open(folder_path + '/real_part_dict.pkl', 'wb') as file:
        pkl.dump(partition_dict, file)

    return bfs_Graph
示例#2
0
    path = "./debugger_input_files/Quality_measure/"
    with open(path+'./qw_3-29.pkl', 'rb') as file:
        qm_weights_old = pkl.load(file)
    with open(path+'./L_3-29.pkl', 'rb') as file:
        qm_L_old = pkl.load( file)

    '''
    Run simulation
    '''
    qm = {}
    # print('\n      N    | Pre-extracted Graph    |')
    # print('           |       qw   |  L        |')
    for N in range(3, 30):
        qm[N] = {}

        partition_dict, dict_seq, node2box_index = quality_measure.partition_set(N)
        _, G_triang = quality_measure.partition(N)

        colors = utils.horizontal_line(N)

        G_bar = pre_extraction.weighted_partition2bar_graph(partition_dict, colors)

        G_pre_extracted = G_bar.copy()
        # print(G_bar.nodes(data=True))
        # filtering
        edges_ = list(G_pre_extracted.edges())
        G_pre_extracted.remove_edges_from(edges_)
        # print('getting graph')

        graph_type = "1"
        min_ = .5
示例#3
0
def img_pre_extr2filtering(image_path,
                           filter_size,
                           beta_d,
                           weighting_method_simplification='ER',
                           entries=[0]):
    '''
    This takes as input a path containing the bfs approximation of the pre-extracted graph. This pre-extracted graph has
     been obtained from an image. The output is the filtered graph.
    :param image_path: string.
    :param filter_size: radious of the filters for the terminal selection process.
    :param weighting_method_simplification: 'ER', 'IBP', 'BPW'.
    :param beta_d: beta input for the DMK solver.
    :return:
        G_filtered: filtered graph (networkx graph).
    '''

    last_word = image_path.split('/')[-1]
    new_folder_name = last_word.split('.')[0]
    saving_path = './runs/' + new_folder_name

    file = '/bfs_extracted_graph.pkl'

    with open(saving_path + file, 'rb') as file:
        Graph = pkl.load(file)

    file = '/real_image.pkl'

    with open(saving_path + file, 'rb') as file:
        color_dict = pkl.load(file)

    file = '/real_part_dict.pkl'

    with open(saving_path + file, 'rb') as file:
        partition_dict = pkl.load(file)

    nbr_graph, color_nbr, terminal_list, nodes_for_correction, filter_number = terminal_computation.terminal_finder(
        filter_size, partition_dict, Graph)
    l = []
    for value in nodes_for_correction.values():
        l += value

    fig, ax = plt.subplots(1, 1, figsize=(15, 15))

    partition_dict_mask, _, _ = quality_measure.partition_set(filter_number +
                                                              1)
    patches = []
    for key in partition_dict_mask:
        square_edges = np.asarray([partition_dict_mask[key][0]] +
                                  [partition_dict_mask[key][2]] +
                                  [partition_dict_mask[key][3]] +
                                  [partition_dict_mask[key][1]] +
                                  [partition_dict_mask[key][0]])
        # print(square_edges)
        # print(len(square_edges))
        s1 = Polygon(square_edges)
        patches.append(s1)
    p = PatchCollection(patches,
                        alpha=.5,
                        linewidth=1,
                        edgecolor='b',
                        facecolor='white')
    ax.add_collection(p)

    patches2 = []
    for key in partition_dict:
        square_edges = np.asarray([partition_dict[key][0]] +
                                  [partition_dict[key][2]] +
                                  [partition_dict[key][3]] +
                                  [partition_dict[key][1]] +
                                  [partition_dict[key][0]])
        # print(square_edges)
        # print(len(square_edges))
        s1 = Polygon(square_edges)
        patches2.append(s1)
    p2 = PatchCollection(patches2,
                         alpha=.4,
                         cmap='YlOrRd',
                         linewidth=.1,
                         edgecolor='b')

    colors = np.array(list(color_dict.values()))
    p2.set_array(colors)
    ax.add_collection(p2)

    pos = nx.get_node_attributes(nbr_graph, 'pos')
    nx.draw_networkx(nbr_graph,
                     pos,
                     node_size=15,
                     width=1.5,
                     with_labels=False,
                     edge_color='red',
                     alpha=1,
                     node_color=color_nbr,
                     ax=ax)

    pos = nx.get_node_attributes(Graph, 'pos')
    nx.draw_networkx(Graph,
                     pos,
                     node_size=0,
                     width=1.5,
                     with_labels=False,
                     edge_color='black',
                     alpha=0.5,
                     ax=ax)

    for i in range(len(terminal_list)):
        node = terminal_list[i]
        # color=color_nbr[i]
        if node in l:
            color = 'green'
            size = 1
        else:
            color = 'black'
            size = .5
        x = Graph.nodes[node]['pos'][0]
        y = Graph.nodes[node]['pos'][1]
        circle1 = plt.Circle((x, y), .01, color=color, fill=False, lw=size)
        ax.add_artist(circle1)
        # label = ax.annotate(str(node), xy=(x, y), fontsize=12, ha="center")

    plt.savefig(saving_path + '/terminal_map.png')

    G_filtered = filtering_from_image(Graph, beta_d, terminal_list, color_dict,
                                      partition_dict,
                                      weighting_method_simplification, entries,
                                      saving_path)
    return G_filtered
示例#4
0
def pre_extraction_from_image(image_path,
                              new_size,
                              t2,
                              number_of_colors=50,
                              number_of_cc=1,
                              graph_type='1',
                              t1=0,
                              reversed_colors=True,
                              t3=1,
                              ds_interpolation='nearest',
                              plotting=False):
    '''
	This takes an image and return a graph extracted from it according to the pre-extraction rules.
	:param image_path: string.
	:param new_size: new size for the input image.
	:param t2: threshold for the weights of the edges after pre-extraction.
	:param number_of_colors: number of colors for the output image.
	:param number_of_cc: number of connected components of the graph represented by the image. If None, then only 1
	cc is assumed.
	:param graph_type: 1 (to use edges and vertices of the grid), 2 (to use only edges).
	:param t1: noise threshold. If t1=0, then all the new pixels are preserved with their new colors.
	:return:
		small_G_pre_extracted: pre-extracted graph.
	'''

    width, color_dict, folder_path = resizing_image(image_path,
                                                    number_of_colors, new_size,
                                                    t1, reversed_colors,
                                                    ds_interpolation)

    N = width + 1
    _, G_triang = quality_measure.partition(N)
    partition_dict, dict_seq, node2box_index = quality_measure.partition_set(N)

    G_bar = weighted_partition2bar_graph(partition_dict, color_dict)

    #max_=max(color_dict.values())

    G_pre_extracted = G_bar.copy()

    # filtering
    edges_ = list(G_pre_extracted.edges())
    G_pre_extracted.remove_edges_from(edges_)

    G_pre_extracted = node_edge_filter(G_pre_extracted,
                                       t2,
                                       graph_type,
                                       dict_seq,
                                       'ER',
                                       'image',
                                       node2box_index,
                                       t3=t3)  # 12

    small_G_pre_extracted = G_pre_extracted.copy()
    small_G_pre_extracted.remove_nodes_from(list(nx.isolates(G_pre_extracted)))
    pos = nx.get_node_attributes(small_G_pre_extracted, 'pos')

    if plotting:

        fig, ax = plt.subplots(1, 1, figsize=(15, 15))
        patches = []
        for key in partition_dict:
            square_edges = np.asarray([partition_dict[key][0]] +
                                      [partition_dict[key][2]] +
                                      [partition_dict[key][3]] +
                                      [partition_dict[key][1]] +
                                      [partition_dict[key][0]])

            s1 = Polygon(square_edges)
            patches.append(s1)
        p = PatchCollection(patches,
                            alpha=.7,
                            cmap='YlOrRd',
                            linewidth=.1,
                            edgecolor='b')

        colors = np.array(list(color_dict.values()))
        p.set_array(colors)
        ax.add_collection(p)

        nx.draw_networkx(small_G_pre_extracted,
                         pos,
                         node_size=1,
                         width=3,
                         with_labels=False,
                         edge_color='Gray',
                         alpha=0.8,
                         node_color='black',
                         ax=ax)

    if number_of_cc in [1, None
                        ] and plotting:  #we assume then there's just one

        plt.savefig(folder_path + '/extracted_graph.png')

        cc_large = max(nx.connected_components(small_G_pre_extracted), key=len)
        small_G_pre_extracted = small_G_pre_extracted.subgraph(cc_large)

        pos = nx.get_node_attributes(small_G_pre_extracted, 'pos')
        nx.draw_networkx(small_G_pre_extracted,
                         pos,
                         node_size=3,
                         width=3,
                         with_labels=False,
                         edge_color='black',
                         alpha=0.8,
                         node_color='black',
                         ax=ax)

    with open(folder_path + '/extracted_graph.pkl', 'wb') as file:
        pkl.dump(small_G_pre_extracted, file)

    with open(folder_path + '/real_image.pkl', 'wb') as file:
        pkl.dump(color_dict, file)

    with open(folder_path + '/G_bar.pkl', 'wb') as file:
        pkl.dump(G_bar, file)

    return small_G_pre_extracted, color_dict, partition_dict, folder_path
示例#5
0
def resizing_image(image_path,
                   number_of_colors,
                   new_size,
                   t=0,
                   reversed_colors=True,
                   ds_interpolation='nearest',
                   plotting=True):
    '''
	This resizes and repaints an image.
	:param image_path: string.
	:param number_of_colors: number of colors for the output image.
	:param t: noise threshold. If t=0, then all the new pixels are preserved with their new colors.
	:return:
		width: width of the output image.
		color_dict: dictionary s.t., color_dict[key]= real value for the key-th pixel.
		key is the index for the pixels in the resized image.
		saving_path: string, to where the new image is saved.
	'''
    if ds_interpolation == 'nearest':
        ds_funct = cv.INTER_NEAREST
    elif ds_interpolation == 'area':
        ds_funct = cv.INTER_AREA

    last_word = image_path.split('/')[-1]
    new_folder_name = last_word.split('.')[0]
    saving_path = './runs/' + new_folder_name

    try:
        os.mkdir(saving_path)
    except:
        pass
    #print('resizing',os.getcwd(), image_path)
    im = Image.open(image_path)
    width, height, = im.size
    pixel_values = np.array(list(im.getdata()))
    im = cv.imread(image_path)

    if new_size == 'automatic':
        new_size = max(int(0.30 * width), 100)

    if width != new_size:
        #resizing it

        img_rotate_90_clockwise = cv.rotate(im, cv.ROTATE_90_CLOCKWISE)

        img_ratio = new_size / width
        #print('ratio:', img_ratio)

        small_to_large_image_size_ratio = img_ratio
        small_img = cv.resize(
            img_rotate_90_clockwise,  # original image
            (0, 0),  # set fx and fy, not the final size
            fx=small_to_large_image_size_ratio,
            fy=small_to_large_image_size_ratio,
            interpolation=ds_funct)
        cv.imwrite(saving_path + '/resized_' + new_folder_name + '.jpg',
                   small_img)
        res_im = Image.open(
            saving_path + '/resized_' + new_folder_name + '.jpg', 'r')
        width, height = res_im.size
        pixel_values = np.array(list(res_im.getdata()))
    else:
        print('new size = current size')

    partition_dict, dict_seq, node2box_index = quality_measure.partition_set(
        width + 1)

    number_of_colors += 1
    i = 0
    color_dict = {}
    for r, b, g in pixel_values:
        rgb = ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff)
        # print(rgb)
        color_dict[i] = int(rgb)
        i += 1
    #print(len(color_dict))
    colors = []
    max_ = max(color_dict.values())
    color_flag = 2

    for key in color_dict.keys():
        if reversed_colors == True:
            color_dict[key] = max(1 - color_dict[key] / max_, t)
        else:
            color_dict[key] = max(color_dict[key] / max_, t)
        # print(color_dict[key])
        #color = coloring(color_dict[key], number_of_colors)

        color = color_dict[key]

        colors.append(color)

    max_ = max(color_dict.values())

    if plotting:

        fig, ax = plt.subplots(1, 1, figsize=(17, 15))
        patches = []
        for key in partition_dict:
            square_edges = np.asarray([partition_dict[key][0]] +
                                      [partition_dict[key][2]] +
                                      [partition_dict[key][3]] +
                                      [partition_dict[key][1]] +
                                      [partition_dict[key][0]])

            s1 = Polygon(square_edges)
            patches.append(s1)
        p = PatchCollection(patches,
                            alpha=1,
                            linewidth=.0,
                            edgecolor='b',
                            cmap='Greys')

        p.set_array(np.array(colors))
        ax.add_collection(p)
        plt.colorbar(p)
        folder_path = image_path.replace(image_path.split('/')[-1], "")

        plt.savefig(saving_path + '/repainted_resized_image.png')
        #plt.show()

    return width, color_dict, saving_path