def graphcut(self, label_costs, l=100): num_classes = len(self.colors_present) #calculate pariwise potiential costs (distance between color classes) pairwise_costs = np.zeros((num_classes, num_classes)) for ii in range(num_classes): for jj in range(num_classes): c1 = np.array(self.label_to_color_map[ii]) c2 = np.array(self.label_to_color_map[jj]) pairwise_costs[ii,jj] = np.linalg.norm(c1-c2) label_costs_int32 = (100*label_costs).astype('int32') pairwise_costs_int32 = (l*pairwise_costs).astype('int32') vv_int32 = (self.g).astype('int32') vh_int32 = (self.g).astype('int32') #vv_int32 = (1/np.clip(self.g,0.00001,10000)).astype('int32') #vh_int32 = (1/np.clip(self.g,0.00001,10000)).astype('int32') #perform graphcut optimization new_labels = pygco.cut_simple_vh(label_costs_int32, pairwise_costs_int32, vv_int32, vh_int32, n_iter=10, algorithm='swap') #new_labels = pygco.cut_simple(label_costs_int32, pairwise_costs_int32, algorithm='swap') return new_labels
def graph_cut(self,im): color_costs = np.zeros((self.num_colors,self.num_colors)) for x in range(self.num_colors): for y in range(self.num_colors): color_costs[x][y] = np.linalg.norm(self.colors[x]-self.colors[y]) color_costs = (color_costs).astype('int32') temp = np.hstack(np.array([-1.0*self.distances[i] for i in range(self.num_colors)])) new_shape = (im.shape[0],im.shape[1],self.num_colors) label_affinity = (100*temp.reshape(new_shape)).astype('int32') blurred = cv2.GaussianBlur(im, (0, 0), 3) vh = cv2.Sobel(blurred, -1, 1, 0) vv = cv2.Sobel(blurred, -1, 0, 1) edges = (0.5*vv + 0.5*vh).astype('int32') gc = pygco.cut_simple_vh(label_affinity, color_costs, edges, edges, n_iter=10, algorithm='swap') return gc