def filter_on_class_size(self, path, class_int, pixel_size=5): """ Filter the classified pixels by a minimum pixel size """ ds = rasterio.open(path) ar = ds.read(1) # Filter for Gully class ar[ar != class_int] = 0 # Set up structure for connectivity and find connectivity structure = np.ones((3, 3), dtype=np.int) labeled, ncomponents = label(ar, structure) # use sklabel to find the sizes of the labels labels = sklabel(ar) unique, counts = np.unique(labels, return_counts=True) label_filt = unique[(counts > 5) & (counts < max(counts))] # Filter based on label size array_filt = labeled == label_filt[0] for l in label_filt: array_filt += labeled == l array_filt = array_filt.astype(int) return array_filt
def get_bounding_boxes_for_single_label(label, obj_type=True, box_type='x1,y1,x2,y2', in_percent=False): boxes = list() label[label != obj_type] = 0 regions = regionprops(sklabel(label)) for region in regions: y1, x1, y2, x2 = region.bbox if in_percent: label_h, label_w = label.shape y1 = y1 / label_h x1 = x1 / label_w y2 = y2 / label_h x2 = x2 / label_w if box_type == 'x1,y1,x2,y2': boxes.append((x1, y1, x2, y2)) elif box_type == 'xm,ym,w,h': w = x2 - x1 h = y2 - y1 xm = x1 + w // 2 ym = y1 + h // 2 boxes.append((xm, ym, w, h)) else: # use 'x1,y1,x2,y2' if wrong format was given boxes.append((x1, y1, x2, y2)) return boxes
def label(self, mask, connectivity=2): """label objects Parameters ---------- mask (numpy.array): mask array, same size with field Returns ------- pass """ label_mask = sklabel(mask, connectivity=connectivity) return label_mask
def centroids_bw(self, im, small_th=2, edge_crop=4): from skimage.measure import label as sklabel from skimage.measure import regionprops as skregionprops centroids = [] sx, sy = im.shape label_ = sklabel(im) for region in skregionprops(label_): if region.area > small_th: cent = region.centroid if cent[0] > edge_crop and cent[1] > edge_crop and sx - cent[ 0] > edge_crop and sy - cent[1] > edge_crop: centroids.append(cent) return centroids
def label_particles_convolve(im, kern, thresh=0.45, **extra_args): """ Given image and kenerl, use the kernel to convolve with the image, if value larger than threshold, make it 1, otherwise 0. use 1 and 0 to build the center segments """ kernel = np.sign(kern) * gdisk(abs(kern) / 4, abs(kern)) convolved = ndimage.convolve(im, kernel) convolved -= convolved.min() convolved /= convolved.max() threshed = convolved > thresh labels = sklabel(threshed, connectivity=1) return labels, convolved, threshed
def largestConnectComponent(bw_img): if np.sum(bw_img)==0: return bw_img labeled_img, num = sklabel(bw_img, neighbors=4, background=0, return_num=True) if num == 1: return bw_img max_label = 0 max_num = 0 for i in range(0,num): print(i) if np.sum(labeled_img == (i+1)) > max_num: max_num = np.sum(labeled_img == (i+1)) max_label = i+1 mcr = (labeled_img == max_label) return mcr.astype(np.int)
def seg_label(label): segs = [] for fg in FG_LABEL: mask = label == fg if torch.sum(mask) > 0: masknp = mask.cpu().numpy().astype(int) seg, forenum = sklabel(masknp, background=0, return_num=True, connectivity=2) seg = torch.LongTensor(seg).cuda() pixelnum = np.zeros(forenum, dtype=int) for i in range(forenum): pixelnum[i] = torch.sum(seg == (i + 1)).item() segs.append([seg, pixelnum]) else: segs.append([mask.long(), np.zeros(0)]) return segs
def maximum_uncertainty_region(data, uncertainty_threshold="mean", morph_opening_struct=None, region_mode="sum"): """Return mask where data has the largest connected region > threshold""" if np.min(data) == np.max(data): return np.ones(data.shape, dtype=np.float32) # set threshold to mean if nothing was specified if uncertainty_threshold == "mean": uncertainty_threshold = np.mean(data) else: uncertainty_threshold = uncertainty_threshold * (np.max(data) - np.min(data)) + np.min(data) thresh_data = data >= uncertainty_threshold if morph_opening_struct is not None: thresh_data = opening(thresh_data, morph_opening_struct) # create thresholded image and image with labeled components regions_labeled = sklabel(thresh_data, background=0) labels = np.unique(regions_labeled) # get uncertainty for each region uncertainties = [0] for label in labels: if label == 0: continue if region_mode == "sum": uncertainty = np.sum(data * (regions_labeled == label)) elif region_mode in ("average", "mean"): uncertainty = np.sum(data * (regions_labeled == label)) / np.float(np.sum(regions_labeled == label)) else: raise ValueError("Unknown option for region_mode: {}".format(region_mode)) uncertainties.append(uncertainty) max_component = np.argmax(uncertainties) # create mask of target region return regions_labeled == max_component
def anchorsbi(label, origin_size=(720,1280), iou_thresh=0.4): h,w = label.shape[0], label.shape[1] h_scale, w_scale = float(origin_size[0])/h, float(origin_size[1])/w hthre = np.ceil(32./h_scale) wthre = np.ceil(32./w_scale) anchors = [] for fg in FG_LABEL: mask = label==fg foreidx = 1 if torch.sum(mask)>0: masknp = mask.cpu().clone().detach().numpy().astype(int) seg, foreidx = sklabel(masknp, background=0, return_num=True, connectivity=2) foreidx += 1 anc_cls = np.zeros((foreidx-1,5)) for fi in range(1, foreidx): x,y = np.where(seg==fi) anc_cls[fi-1,:4] = np.min(x), np.min(y), np.max(x), np.max(y) area = (anc_cls[fi-1,2] - anc_cls[fi-1,0])*(anc_cls[fi-1,3] - anc_cls[fi-1,1]) anc_cls[fi-1,4] = float(len(x)) / max(area, 1e-5) if len(anc_cls) > 0: hdis = anc_cls[:,2] - anc_cls[:,0] wdis = anc_cls[:,3] - anc_cls[:,1] anc_cls = anc_cls[np.where((hdis>=hthre)&(wdis>=wthre))[0],:] area = (anc_cls[:,2] - anc_cls[:,0])*(anc_cls[:,3] - anc_cls[:,1]) sortidx = np.argsort(area)[::-1] anc_cls = anc_cls[sortidx,:] if len(anc_cls) > 0: anc_cls = anc_cls[np.where(anc_cls[:,4]>=iou_thresh)[0],:] if len(anc_cls) > 0: anc_cls[:,0] = np.floor(h_scale*anc_cls[:,0]) anc_cls[:,2] = np.ceil(h_scale*anc_cls[:,2]) anc_cls[:,2] = np.where(anc_cls[:,2]<origin_size[0], anc_cls[:,2], origin_size[0]) anc_cls[:,1] = np.ceil(w_scale*anc_cls[:,1]) anc_cls[:,3] = np.ceil(w_scale*anc_cls[:,3]) anc_cls[:,3] = np.where(anc_cls[:,3]<origin_size[1], anc_cls[:,3], origin_size[1]) anchors.append(anc_cls) return anchors
## from here do pore segmentation, i.e. connected components after cutting in dz_pnm thick slices # pnm_domain = sim_domain pnm_domain = np.zeros(sim_domain.shape, dtype = np.uint16) num_segments = int(sim_domain.shape[2]/dz_pnm) + 1 ref_color = 0 for i in range(num_segments): z_pnm_0 = i*dz_pnm if z_pnm_0 > pnm_domain.shape[2]-1: continue z_pnm_1 = min(z_pnm_0 + dz_pnm, pnm_domain.shape[2]) test_volume = sim_domain[:,:,z_pnm_0:z_pnm_1] label = sklabel(test_volume, connectivity = 2) num_pores = label.max() label[np.where(label>0)] = label[np.where(label>0)] + ref_color pnm_domain[:, :, z_pnm_0:z_pnm_1] = label ref_color = ref_color + num_pores bb = ndimage.find_objects(pnm_domain>0)[0] pnm_domain = pnm_domain[bb] pnm_domain.tofile(dest_PNM)