我们从Python开源项目中,提取了以下2个代码示例,用于说明如何使用cv2.connectedComponents()。
def run(self, ips, snap, img, para = None): a, msk = cv2.connectedComponents(ips.get_msk().astype(np.uint8)) msk = cv2.watershed(img, msk)==-1 img //= 2 img[msk] = 255
def parallel_processing(index,superpixel_data,superpixel_images,place_to_save): print index current_superpixel_data = cPickle.load(open(superpixel_data[index], "rb")) to_be_saved_file_name=superpixel_data[index].split('/')[-1][:-11]+'_merged.png' to_be_saved_data_name = superpixel_data[index].split('/')[-1][:-11] + '_merged.dat' # statisticst num_superpixels=len(current_superpixel_data[0]) superpixel_labels=current_superpixel_data[1] # find unique labels unique_labels=find_unique_labels(current_superpixel_data) # iterate: assign updated labels for all superpixels return_map=assign_updated_labels(num_superpixels,current_superpixel_data,unique_labels) # plt.imshow(current_superpixel_data[1]) # plt.show() print "Finding connected component for "+str(index)+' '+superpixel_data[index].split('/')[-1] new_superpixel_label=0 chosen_label_values=[] final_map=np.ones((1024,2048))*(num_superpixels+10) for index_unique_label,unique_label in enumerate(unique_labels): current_unique_label_layer=return_map==index_unique_label current_unique_label_layer=current_unique_label_layer.astype(np.uint8) current_unique_label_layer_connected_component=cv2.connectedComponents(current_unique_label_layer, connectivity=8) total_connected_components=current_unique_label_layer_connected_component[0] # plt.imshow(current_unique_label_layer_connected_component[1]) # plt.show() for index_connected_component in range(1,total_connected_components): # chosen_label_value=np.random.choice(label_array) final_map[current_unique_label_layer_connected_component[1]==index_connected_component]=new_superpixel_label # label_array.remove(chosen_label_value) chosen_label_values.append(new_superpixel_label) new_superpixel_label=new_superpixel_label+1 # render my_palette=palette(new_superpixel_label) result_img = Image.fromarray(final_map.astype(np.uint8)).convert('P') result_img.putpalette(my_palette) result_img.save(os.path.join(place_to_save, 'visualization', to_be_saved_file_name)) # save data final_superpixel_data=current_superpixel_data+(final_map,unique_labels,chosen_label_values) cPickle.dump(final_superpixel_data, open(os.path.join(place_to_save, 'data', to_be_saved_data_name), "w+"))