def assign_gt_to_ws(self, gt): ws_nopad = morpho.juicy_center(self.watershed, self.pad_thickness) bdrymap = morpho.pad(morpho.seg_to_bdry(ws_nopad), [0] * self.pad_thickness) gt_bdrymap_nopad = morpho.seg_to_bdry(gt) gt_bdrymap = morpho.pad(gt_bdrymap_nopad, [0] * self.pad_thickness) k = distance_transform_cdt(1 - bdrymap, return_indices=True) ind = nonzero(gt_bdrymap.ravel())[0] closest_sub = numpy.concatenate([i.ravel()[:, newaxis] for i in k[1]], axis=1) closest_sub = closest_sub[ind, :] closest_ind = [ dot(bdrymap.strides, i) / bdrymap.itemsize for i in closest_sub ] M = zeros_like(bdrymap).astype(float) M.ravel()[closest_ind] = 1.0 bdrymap.ravel()[closest_ind] = False k = distance_transform_cdt(1 - bdrymap, return_indices=True) ind = nonzero(gt_bdrymap.ravel())[0] closest_sub = numpy.concatenate([i.ravel()[:, newaxis] for i in k[1]], axis=1) closest_sub = closest_sub[ind, :] closest_ind = [ dot(bdrymap.strides, i) / bdrymap.itemsize for i in closest_sub ] M.ravel()[closest_ind] = 1.0 return M
def assign_gt_to_ws(self, gt): ws_nopad = morpho.juicy_center(self.watershed, self.pad_thickness) bdrymap = morpho.pad(morpho.seg_to_bdry(ws_nopad), [0]*self.pad_thickness) gt_bdrymap_nopad = morpho.seg_to_bdry(gt) gt_bdrymap = morpho.pad(gt_bdrymap_nopad, [0]*self.pad_thickness) k = distance_transform_cdt(1-bdrymap, return_indices=True) ind = nonzero(gt_bdrymap.ravel())[0] closest_sub = numpy.concatenate( [i.ravel()[:,newaxis] for i in k[1]],axis=1) closest_sub = closest_sub[ind,:] closest_ind = [dot(bdrymap.strides, i)/bdrymap.itemsize for i in closest_sub] M = zeros_like(bdrymap).astype(float) M.ravel()[closest_ind]=1.0 bdrymap.ravel()[closest_ind] = False k = distance_transform_cdt(1-bdrymap, return_indices=True) ind = nonzero(gt_bdrymap.ravel())[0] closest_sub = numpy.concatenate( [i.ravel()[:,newaxis] for i in k[1]],axis=1) closest_sub = closest_sub[ind,:] closest_ind = [dot(bdrymap.strides, i)/bdrymap.itemsize for i in closest_sub] M.ravel()[closest_ind]=1.0 return M
def kanungo_degrade(image, eta=0.0, alpha=1.5, beta=1.5, alpha_0=1.0, beta_0=1.0, do_closing=True): """Degrade image using method from Kanungo, T., Haralick, R. M., Baird, H. S., Stuezle, W., & Madigan, D. (2000). A statistical, nonparametric methodology for document degradation model validation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(11), 1209-1223. :param image: [h, w] 8-bit grayscale image :param eta: :param alpha: :param beta: :param alpha_0: :param beta_0: :param do_closing: whether to perform morphological closing of the result :return: """ # invert and image = np.amax(image) - image image = image / np.amax(image) # flip foreground pixels fg_dist = distance_transform_cdt(image, metric='taxicab') fg_prob = alpha_0 * np.exp(-alpha * (fg_dist**2)) + eta fg_prob[image == 0] = 0 fg_flip = np.random.binomial(1, fg_prob) bg_dist = distance_transform_cdt(1 - image, metric='taxicab') bg_prob = beta_0 * np.exp(-beta * (bg_dist**2)) + eta bg_prob[image == 1] = 0 bg_flip = np.random.binomial(1, bg_prob) bg_mask = np.ma.make_mask(bg_flip) fg_mask = np.ma.make_mask(fg_flip) result = np.copy(image) result[bg_mask] = 1 - result[bg_mask] result[fg_mask] = 1 - result[fg_mask] if do_closing: sel = np.array([ [1, 1], [1, 1], ]) result = binary_closing(result, sel) # result = 255 - result.astype(np.uint8) * 255 result = 1. - result.astype('float32') return result
def distance_transform_image(image): data = np.vstack(np.asarray(image).astype(np.float32)) mdt = ndi.distance_transform_cdt(data, metric='chessboard').astype('float32') ldt = ndi.distance_transform_cdt(data, metric='taxicab').astype('float32') edt = ndi.distance_transform_edt(data).astype('float32') imgMDT = Image.fromarray(mdt).convert('L') imgLDT = Image.fromarray(ldt).convert('L') imgEDT = Image.fromarray(edt).convert('L') return Image.merge('RGB', (imgLDT, imgEDT, imgMDT))
def Generate_negative_sample_our(pathfolder_mrxs, pathfolder_imgBin,pathfolder_labelmap, filename, level,numSample, size): """ 从阳性图中随机取阴性图,返回20倍坐标 """ size = int(size/2) pathmrxs = pathfolder_mrxs + filename + '.svs' pathimgBin = pathfolder_imgBin + filename + '.tif' pathlabelmap = pathfolder_labelmap + filename + '.tif' leveltemp = 2 # 与缩略图相对原图尺寸变化有关 #######得到目标前景 imgBin = cv2.imread(pathimgBin) labelmap = cv2.imread(pathlabelmap) labelmap[labelmap==255] = 1 labelmap = 1-labelmap labelmap = ndi.distance_transform_cdt(labelmap.copy()) dis = int(size * (2 ** level) / (2 ** leveltemp)) labelmap [labelmap ==-1] = 255 imgBin[labelmap < dis] = 0 imgMask = imgBin[:, :, 0] + imgBin[:, :, 1] + imgBin[:, :, 2] imgMask[imgMask > 0] = 1 #######随机选择numSample个点 imgCon = imgMask.copy() ind = np.flatnonzero(imgCon) ind = ind[np.random.randint(np.size(ind), size = numSample*10)] indRow, indCol = np.unravel_index(ind, np.shape(imgCon)) sizetemp = size*(4**level)/(4**leveltemp) temp1 = np.logical_and(indRow > sizetemp+1, indRow < imgCon.shape[0]-sizetemp-1) temp2 = np.logical_and(indCol > sizetemp+1, indCol < imgCon.shape[1]-sizetemp-1) temp3 = np.logical_and(temp1, temp2) indRow = indRow[temp3] indCol = indCol[temp3] return indRow,indCol
def get_bg_dict(background): distance = distance_transform_cdt(background.squeeze()) sp_mask = (slic(distance, n_segments=5, compactness=10) + 1) * (distance != 0) mask_pos = np.where(background.squeeze()) mask_neg = np.where(1 - background.squeeze()) regionList = regionprops(sp_mask) # for l in np.unique(sp_mask): # if l == 0: # continue # mask = sp_mask == l # dis = distance_transform_cdt(mask) # yx = np.where(dis==np.median(dis[dis>0])) yList = [] xList = [] for region in regionList: centroid = region.centroid y = int(centroid[0]) x = int(centroid[1]) yList += [y] xList += [x] return { "xList": xList, "yList": yList, "mask_pos": mask_pos, "mask_neg": mask_neg }
def label_erosion(label, distance, metric='chessboard'): """ Erode labeled area in label array by given distance (in pixels) The erosion is done with respect to background only, not other label. Thus connected label stay connected, if the touching pixels are far enough from the background. Input: label: a label array distance: a scalar indicating the euclidian distance metric: if 'chessbord', use chessbord distance if 'taxicab', use taxicap distance otherwise, use euclidian distance (slower) """ ##todo: as fast, use bin erosion (grey erosion is no use)? # what about distance ? use big (ellipse) structure, or low with iterations ? if metric in ('taxicab', 'chessboard'): dist, ind = _nd.distance_transform_cdt(label != 0, return_indices=True, metric=metric) else: dist, ind = _nd.distance_transform_edt(label != 0, return_indices=True) ero_label = label.copy() ero_label[dist <= distance] = 0 return ero_label
def tracePerimeter(im): distance = ndimage.distance_transform_cdt(im, metric='taxicab') #distance[distance!=1] = 0 #distance = ndimage.distance_transform_edt(im) distance[distance > 3] = 0 distance[distance < 1] = 0 return distance
def label_erosion(label, distance, metric='chessboard'): """ Erode labeled area in label array by given distance (in pixels) The erosion is done with respect to background only, not other label. Thus connected label stay connected, if the touching pixels are far enough from the background. Input: label: a label array distance: a scalar indicating the euclidian distance metric: if 'chessbord', use chessbord distance if 'taxicab', use taxicap distance otherwise, use euclidian distance (slower) """ ##todo: as fast, use bin erosion (grey erosion is no use)? # what about distance ? use big (ellipse) structure, or low with iterations ? if metric in ('taxicab','chessboard'): dist, ind = _nd.distance_transform_cdt(label!=0, return_indices=True,metric=metric) else: dist, ind = _nd.distance_transform_edt(label!=0, return_indices=True) ero_label = label.copy() ero_label[dist<=distance] = 0 return ero_label
def gray2triplewithbound(gray, n_classes=4, width=1): """ convert gray to triple seg with bounds """ h, w = gray.shape[:2] gray[gray == 76] = 255 gray[gray == 151] = 255 label = gray2mask(gray) label_binary = label_binarize(label.flatten(), classes=range(0, 3)) label_binary = np.reshape(label_binary, (h, w, -1)) bound_binary = np.zeros_like(label_binary) for i in range(3): # number of classes before edge detection tmp = ndimage.distance_transform_cdt(label_binary[:, :, i], 'taxicab') cdt = np.logical_and(tmp >= 1, tmp <= width) bound_binary[:, :, i] = cdt bound = np.any(bound_binary, axis=2) mask = np.zeros((h, w), dtype=np.uint8) mask[gray == 255] = 2 mask[gray == 29] = 1 if n_classes == 4: mask[bound] = 3 elif n_classes == 5: mask[bound_binary[:, :, 1] == 1] = 3 # inner boundary mask[bound_binary[:, :, 0] == 1] = 4 # outer boundary return mask
def colorVessels(self,binary_ves,color_depthMAT): ########################################################################### ## Colouring the vessels based on depth. ########################################################################### rows,cols = binary_ves.shape edge1 = roberts(binary_ves) edge2,edge3 = np.gradient(color_depthMAT) animateFlow.distance = ndimage.distance_transform_cdt(binary_ves , return_distances=True) animateFlow.distance=animateFlow.distance.transpose() animateFlow.width_ave=self.ave(animateFlow.distance) img = pygame.surfarray.make_surface(binary_ves).convert() for i in range(0,rows): for j in range(0,cols): if img.get_at((i,j))!=(0,0,0,255): if edge1[i][j]>0: img.set_at((i,j),(120,120,120,180)) elif edge2[j][i] >= 1.2 * animateFlow.depth_range or edge3[j][i] >= 1.2 * animateFlow.depth_range: img.set_at((i,j),(120,120,120,180)) else: fill = 0 # i_c = -2 while i_c < 2 and fill == 0: i_c += 1 j_c = -2 while j_c <2 and fill == 0: j_c += 1 if 0 <= j+j_c < cols and 0 <= i+i_c < rows: if abs(color_depthMAT[j][i]-color_depthMAT[j+j_c][i+i_c]) < 1*animateFlow.depth_range and img.get_at((i,j))!=(0, 0, 85, 255): color = img.get_at((i,j)) fill = 1 break if fill == 0: if 0<color_depthMAT[j][i]<=40: color = (255,0,0,180) elif color_depthMAT[j][i]<=80: color = (220,0,0,180) elif color_depthMAT[j][i]<=120: color = (200,0,0,180) elif color_depthMAT[j][i]<=160: color = (180,0,0,180) elif color_depthMAT[j][i]<=200: color = (150,0,0,180) elif color_depthMAT[j][i]<=240: color = (120,0,0,180) else: color = (100,0,0,180) img.set_at((i,j),color) return img
def readImage(self): sitkimg = sitk.ReadImage(self.imgfile) self.simg = sitk.GetArrayFromImage(sitkimg) self.dfe = ndi.distance_transform_cdt(self.simg) cg = self.sg.orderedGraphs[self.key] self.sg.spacing=cg.graph["spacing"] self.sg.origin=cg.graph["origin"] self.points_toMap = np.array(np.nonzero(np.where(self.simg==self.lvalue,1,0))[::-1]).transpose().astype(np.int32)
def render(self, samples): n = self.n target = zeros([n, n], 'f') for i, j in samples: target[i, j] = 1.0 d = ndi.distance_transform_cdt(target == 0) target = 1.0 * (d < maximum(self.minsize, self.ys * self.scale)) return target
def reach_cost(reachable): cost = np.empty(reachable.shape, float) reachable = reachable.astype('bool') reachable_region_cost = -ndi.distance_transform_cdt(reachable) np.putmask(cost, reachable, reachable_region_cost) np.putmask(cost, ~reachable, IKFAIL_COST) return cost
def reach_cost(reachable): cost = np.empty(reachable.shape, float) reachable = reachable.astype('bool') reachable_region_cost = - ndi.distance_transform_cdt(reachable) np.putmask(cost,reachable,reachable_region_cost) np.putmask(cost,~reachable, IKFAIL_COST) return cost
def process_time_step(t, water): dt = ndimage.distance_transform_cdt(water) dt_inv = ndimage.distance_transform_cdt(~water) water_interface = dt==1 Area1 = np.count_nonzero(water_interface) Area2 = np.count_nonzero(dt_inv==1) Area = (Area1+Area2)/2 water_air_interface = interface_checker(water, water_interface, t, radius = 1) Area_int1 = np.count_nonzero(water_air_interface) Area_int2 = np.count_nonzero(ndimage.distance_transform_cdt(water_air_interface)==1) Area_int = (Area_int1+Area_int2)/2 Area_wet = Area - Area_int return Area_int, Area_wet
def generateRawFigureOfMeritData(self): """This function takes the mask file associated with self and computes a distance from edge map using scipy.ndimage.distance_transform_cdt. The resulting distance map is assigned to a rawFigureOfMerit attribute of self""" try: dfe = ndi.distance_transform_cdt(self.mask) self.rawFigureOfMerit = dfe.take(self.inds) except Exception as error: print("failed in generateRawFigureOfMeritData", error)
def obstacle_cost(free): free = free.astype('bool') cost = np.empty(free.shape, float) free_region_cost = -ndi.distance_transform_cdt(free) np.putmask(cost, free, free_region_cost) np.putmask(cost, ~free, COLLISION_COST) return cost
def obstacle_cost(free): free = free.astype('bool') cost = np.empty(free.shape, float) free_region_cost = - ndi.distance_transform_cdt(free) np.putmask(cost,free,free_region_cost) np.putmask(cost,~free, COLLISION_COST) return cost
def compute_loss_map(array): if len(array.shape) == 4: array = array[0, :, :, 0] interior = binary_erosion(array) invert = np.logical_not(array).astype(int) # mult_mask = np.add(np.multiply(-1,array),invert) contour = array - interior dist = distance_transform_cdt(np.logical_not(contour).astype(int), metric="taxicab") # return np.multiply(dist, mult_mask) return dist
def generateWalkingDistMask(self, max_walking_distance): temp = np.zeros((self.nb_rows + 2 * max_walking_distance, self.nb_columns + 2 * max_walking_distance), np.int32) temp[max_walking_distance:max_walking_distance + self.nb_rows, max_walking_distance:max_walking_distance + self.nb_columns] = self.plan temp = 1 - temp # the mask is generated from the distance tranform to any border cell of a building dist = distance_transform_cdt(temp, 'manhattan') self.manhattan_mask = np.multiply( np.where(dist <= max_walking_distance, 1, 0), temp)
def main(): simg, descr = readImage(sys.argv[1]) pool = mp.Pool(mp.cpu_count()) try: simg except: sys.exit("read of skeleton image failed") sg = SkeletonGraph(img=simg, spacing=descr['scale'], origin=descr['origin'], orientation=descr['orientation'], label=sys.argv[1], pool=pool) ##print descr #print sg.spacing, sg.origin, sg.orientation oimg, tmp = readImage(sys.argv[2]) try: oimg except: sys.exit("read of mask image failed") sg.setOriginalImage(oimg) sg.getGraphsFromSkeleton(verbose=True) sg.setLargestGraphToCurrentGraph() list(sg.graphs.keys()) sg.findEndpointsBifurcations() print("set root") root = rootRMS(sg.cg) #sg.viewGraph() sg.setRoot(root, key="og_rms") print("trace endpoints") sg.traceEndpoints(key='og_rms') ogkey = sg.getLargestOrderedGraphKey() print("prune tree") sg.deleteDegree2Nodes(ogkey) sg.prunePaths(ogkey) sg.deleteDegree2Nodes(ogkey) print("fit edges") sg.fitEdges(key=ogkey) print("Define orthogonal planes") sg.defineOrthogonalPlanes(ogkey) print("Now get surface points of original image to map to the centerlines") dfe = ndi.distance_transform_cdt(oimg) points_toMap = np.array(np.nonzero(np.where( dfe == 1, 1, 0))[::-1]).transpose().astype(np.int32) print("mapVoxelsToGraph") sg.mapVoxelsToGraph(points_toMap, ogkey) print("assignMappedPointsToPlanes") sg.assignMappedPointsToPlanes(ogkey) sg.saveCompressedGraphs(sys.argv[3])
def tracePerimeter(im): ''' Chart the perimeter of a binary image. ------------------------------- Input: im --> Binary image Output: perimeter --> Perimeter of the binary image ''' perimeter = ndimage.distance_transform_cdt(im, metric='taxicab') perimeter[perimeter > 3] = 0 perimeter[perimeter < 1] = 0 return perimeter
def generateRawFigureOfMeritData(self): """This function takes the msk file associated with self and computes a distance from edge map using scipy.ndimage.distance_transform_cdt The resulting distance map is assigned to a rawFigureOfMerit attribute of self""" try: dfe = ndi.distance_transform_cdt(self.mask) self.rawFigureOfMerit = dfe.take(self.inds) except Exception, error: print "failed in generateRawFigureOfMeritData", error
def main(): simg,descr = readImage( sys.argv[1] ) pool = mp.Pool(mp.cpu_count()) try: simg except: sys.exit("read of skeleton image failed") sg = SkeletonGraph(img=simg, spacing=descr['scale'], origin=descr['origin'], orientation=descr['orientation'], label = sys.argv[1], pool = pool) ##print descr #print sg.spacing, sg.origin, sg.orientation oimg,tmp = readImage( sys.argv[2]) try: oimg except: sys.exit("read of mask image failed") sg.setOriginalImage(oimg) sg.getGraphsFromSkeleton(verbose=True) sg.setLargestGraphToCurrentGraph() list(sg.graphs.keys()) sg.findEndpointsBifurcations() print("set root") root = rootRMS(sg.cg) #sg.viewGraph() sg.setRoot(root,key="og_rms") print("trace endpoints") sg.traceEndpoints(key='og_rms') ogkey = sg.getLargestOrderedGraphKey() print("prune tree") sg.deleteDegree2Nodes(ogkey) sg.prunePaths(ogkey) sg.deleteDegree2Nodes(ogkey) print("fit edges") sg.fitEdges(key=ogkey) print("Define orthogonal planes") sg.defineOrthogonalPlanes(ogkey) print("Now get surface points of original image to map to the centerlines") dfe = ndi.distance_transform_cdt(oimg) points_toMap = np.array(np.nonzero(np.where(dfe==1,1,0))[::-1]).transpose().astype(np.int32) print("mapVoxelsToGraph") sg.mapVoxelsToGraph(points_toMap,ogkey) print("assignMappedPointsToPlanes") sg.assignMappedPointsToPlanes(ogkey) sg.saveCompressedGraphs(sys.argv[3])
def reconstructVessels(im,skeldepth,skel,convalue_n): global depthrange,skel_dis depthrange=np.mean(skeldepth[skeldepth>0])/LEVEL distance = ndimage.distance_transform_cdt(im , return_distances=True) skel_dis= skel * distance #savemat('..//data//skel_dis.mat',{'skel_dis':skel_dis}) binary_ves,depth=buildVessels(skel,skeldepth,convalue_n) # colored_ves=skel_dep,binary_ves) return binary_ves,depth
def undam(seg): """ Assign zero-dams to nearest non-zero region. """ bdrymap = seg==0 k = distance_transform_cdt(bdrymap, return_indices=True) ind = nonzero(bdrymap.ravel())[0] closest_sub = concatenate([i.ravel()[:,newaxis] for i in k[1]],axis=1) closest_sub = closest_sub[ind,:] closest_ind = [dot(bdrymap.strides, i)/bdrymap.itemsize for i in closest_sub] sp = seg.shape seg = seg.ravel() seg[ind] = seg[closest_ind] seg = reshape(seg, sp) return seg
def interface_tracker(binary, solid=True, dist=1): # returns interface pixels of binary image (pixels draping the true-phase) # ball = skimage.morphology.ball # if len(binary.shape)==2: # ball = skimage.morphology.disk # struct=ball(1) # if solid: struct=ball(1.5) # dilated=skimage.morphology.dilation(binary,selem=struct) # interface=np.bitwise_xor(dilated,binary) interface = ndi.distance_transform_cdt(binary) == dist return interface
def main(): simg, descr = readImage(sys.argv[1]) try: simg except: sys.exit("read of skeleton image failed") sg = SkeletonGraph(img=simg, spacing=descr['scale'], origin=descr['origin'], orientation=descr['orientation'], label=sys.argv[1]) ##print descr #print sg.spacing, sg.origin, sg.orientation oimg, tmp = readImage(sys.argv[2]) try: oimg except: sys.exit("read of mask image failed") sg.setOriginalImage(oimg) sg.getGraphsFromSkeleton(verbose=False) sg.setLargestGraphToCurrentGraph() list(sg.graphs.keys()) sg.findEndpointsBifurcations() endp = [n for n in sg.cg.nodes() if sg.cg.degree(n) == 1] endpa = np.array(endp) medianx = np.median(endpa[:, 0]) endp.sort(key=lambda n: abs(n[0] - medianx)) root = endp[0] #sg.viewGraph() sg.setRoot(root, key="og_medianx") sg.traceEndpoints(key='og_medianx') ogkey = sg.getLargestOrderedGraphKey() sg.deleteDegree2Nodes(ogkey) sg.prunePaths(ogkey) sg.deleteDegree2Nodes(ogkey) sg.fitEdges(key=ogkey) #print "Define orthogonal planes" sg.defineOrthogonalPlanes(ogkey) # Now get surface points of original image to map to the centerlines dfe = ndi.distance_transform_cdt(oimg) points_toMap = np.array(np.nonzero(np.where( dfe == 1, 1, 0))[::-1]).transpose().astype(np.int32) #print "mapVoxelsToGraph" sg.mapVoxelsToGraph(points_toMap, ogkey) #print "assignMappedPointsToPlanes" sg.assignMappedPointsToPlanes(ogkey) sg.saveCompressedGraphs(sys.argv[3])
def _peak_search_skimage(image, **kwargs): '''Default peak detection method: skimage.morphology.get_m**ima (either minima or maxima) Since skimage doesn't handle masked arrays, the masking is a bit of a bodge job here. The basic plan is as follows: * Set the area of the image covered by the mask to a value that cannot include a maxima (or minima, as appropriate) * Search for peak coordinates * Check if, after rounding, any of the peaks are outside the image dimensions * Check if, after rounding, any of the peaks are extremely close to the mask Since the mask is a ahrd-edged area, if there is even a slight rise just outside it, spurious peaks can be detected. Therefore, we automatically reject any peaks for a short distance outside the actual mask ''' connectivity = 2 get_maxima = kwargs.get("maxima", True) mask = kwargs.get("mask", np.zeros(image.shape, dtype=bool)) image_copy = image.copy() if get_maxima: image_copy[mask] = np.nanmin(image_copy) regionalMaxMap = morphology.local_maxima(image_copy, connectivity=connectivity, allow_borders=True) else: image_copy[mask] = np.nanmax(image_copy) regionalMaxMap = morphology.local_minima(image_copy, connectivity=connectivity, allow_borders=True) labelled_max = measure.label(regionalMaxMap, connectivity=connectivity) regions = measure.regionprops(labelled_max) peak_coords = np.zeros(shape=(len(regions), 2), dtype=np.int) distance_from_mask = distance_transform_cdt(image_copy * (1 - mask)) for i, props in enumerate(regions): y0, x0 = props.centroid peak = np.array([y0, x0]) # ensure that there are no peaks off the map (due to rounding) peak[peak < 0] = 0 for j in range(image_copy.ndim): if peak[j] > image_copy.shape[j]: peak[j] = image_copy.shape[j] - 1 peak_index = tuple( np.round(peak, 0).astype(int) ) # indexing with a floating point array sucks, so convert to a more convenient form if distance_from_mask[peak_index] > 2 * connectivity: peak_coords[i, :] = peak return peak_coords
def find_cells(nuclei, mask, remove_boundary_cells=True): """Convert binary mask to cell labels, based on nuclei labels. Expands labeled nuclei to cells, constrained to where mask is >0. """ distance = ndimage.distance_transform_cdt(nuclei == 0) cells = skimage.morphology.watershed(distance, nuclei, mask=mask) # remove cells touching the boundary if remove_boundary_cells: cut = np.concatenate( [cells[0, :], cells[-1, :], cells[:, 0], cells[:, -1]]) cells.flat[np.in1d(cells, np.unique(cut))] = 0 return cells.astype(np.uint16)
def gray2outerbound(gray, width): """ convert grayscale annotation to outer bound """ h, w = gray.shape[:2] gray[gray == 76] = 255 gray[gray == 151] = 255 label = gray2mask(gray) label_binary = label_binarize(label.flatten(), classes=range(0, 3)) label_binary = np.reshape(label_binary, (h, w, -1)) tmp = ndimage.distance_transform_cdt(label_binary[:, :, 0], 'taxicab') outer_bound = np.logical_and(tmp >= 1, tmp <= width).astype(np.uint8) return outer_bound
def undam(seg): """ Assign zero-dams to nearest non-zero region. """ bdrymap = seg==0 k = distance_transform_cdt(bdrymap, return_indices=True) ind = nonzero(bdrymap.ravel())[0] closest_sub = concatenate([i.ravel()[:,newaxis] for i in k[1]],axis=1) closest_sub = closest_sub[ind,:] closest_ind = [ dot(bdrymap.strides, i)/bdrymap.itemsize for i in closest_sub] sp = seg.shape seg = seg.ravel() seg[ind] = seg[closest_ind] seg = reshape(seg, sp) return seg
def main(): simg,descr = readImage( sys.argv[1] ) try: simg except: sys.exit("read of skeleton image failed") sg = SkeletonGraph(img=simg, spacing=descr['scale'], origin=descr['origin'], orientation=descr['orientation'], label = sys.argv[1]) ##print descr #print sg.spacing, sg.origin, sg.orientation oimg,tmp = readImage( sys.argv[2]) try: oimg except: sys.exit("read of mask image failed") sg.setOriginalImage(oimg) sg.getGraphsFromSkeleton(verbose=False) sg.setLargestGraphToCurrentGraph() list(sg.graphs.keys()) sg.findEndpointsBifurcations() endp = [n for n in sg.cg.nodes() if sg.cg.degree(n)==1] endpa = np.array(endp) medianx = np.median(endpa[:,0]) endp.sort(key=lambda n: abs(n[0]-medianx)) root = endp[0] #sg.viewGraph() sg.setRoot(root,key="og_medianx") sg.traceEndpoints(key='og_medianx') ogkey = sg.getLargestOrderedGraphKey() sg.deleteDegree2Nodes(ogkey) sg.prunePaths(ogkey) sg.deleteDegree2Nodes(ogkey) sg.fitEdges(key=ogkey) #print "Define orthogonal planes" sg.defineOrthogonalPlanes(ogkey) # Now get surface points of original image to map to the centerlines dfe = ndi.distance_transform_cdt(oimg) points_toMap = np.array(np.nonzero(np.where(dfe==1,1,0))[::-1]).transpose().astype(np.int32) #print "mapVoxelsToGraph" sg.mapVoxelsToGraph(points_toMap,ogkey) #print "assignMappedPointsToPlanes" sg.assignMappedPointsToPlanes(ogkey) sg.saveCompressedGraphs(sys.argv[3])
def main(): parser = getParser() options = parser.parse_args() itkimg = sitk.ReadImage(options.skel_img) simg = sitk.GetArrayFromImage(itkimg) try: simg except: sys.exit("read of skeleton image failed") sg = SkeletonGraph(img=simg, spacing=itkimg.GetSpacing(), origin=itkimg.GetOrigin(), orientation=itkimg.GetDirection(), label=options.skel_img) print(sg.spacing, sg.origin, sg.orientation) oimg = sitk.GetArrayFromImage(sitk.ReadImage(options.orig_img)) try: oimg except: sys.exit("read of mask image failed") sg.setOriginalImage(oimg) sg.getGraphsFromSkeleton(verbose=False) sg.setLargestGraphToCurrentGraph() list(sg.graphs.keys()) sg.findEndpointsBifurcations() root = sg.selectSeedFromDFE() #sg.viewGraph() #raw_input('continue') sg.setRoot(root, key="mp_graphs") sg.traceEndpoints(key='mp_graphs') ogkey = sg.getLargestOrderedGraphKey() sg.deleteDegree2Nodes(ogkey) sg.prunePaths(ogkey, options.prune_length) sg.deleteDegree2Nodes(ogkey) sg.fitEdges(key=ogkey) print("Define orthogonal planes") sg.defineOrthogonalPlanes(ogkey) # Now get surface points of original image to map to the centerlines dfe = ndi.distance_transform_cdt(oimg) points_toMap = np.array(np.nonzero(np.where( dfe == 1, 1, 0))[::-1]).transpose().astype(np.int32) print("mapVoxelsToGraph") sg.mapVoxelsToGraph(points_toMap, ogkey, verbose=True) print("assignMappedPointsToPlanes") sg.assignMappedPointsToPlanes(ogkey) sg.saveCompressedGraphs(options.graph_file)
def main(): parser = getParser() options = parser.parse_args() itkimg = sitk.ReadImage(options.skel_img) simg = sitk.GetArrayFromImage(itkimg) try: simg except: sys.exit("read of skeleton image failed") sg = SkeletonGraph(img=simg, spacing=itkimg.GetSpacing(), origin=itkimg.GetOrigin(), orientation=itkimg.GetDirection(), label = options.skel_img) print(sg.spacing, sg.origin, sg.orientation) oimg = sitk.GetArrayFromImage(sitk.ReadImage(options.orig_img)) try: oimg except: sys.exit("read of mask image failed") sg.setOriginalImage(oimg) sg.getGraphsFromSkeleton(verbose=False) sg.setLargestGraphToCurrentGraph() list(sg.graphs.keys()) sg.findEndpointsBifurcations() root = sg.selectSeedFromDFE() #sg.viewGraph() #raw_input('continue') sg.setRoot(root,key="mp_graphs") sg.traceEndpoints(key='mp_graphs') ogkey = sg.getLargestOrderedGraphKey() sg.deleteDegree2Nodes(ogkey) sg.prunePaths(ogkey,options.prune_length) sg.deleteDegree2Nodes(ogkey) sg.fitEdges(key=ogkey) print("Define orthogonal planes") sg.defineOrthogonalPlanes(ogkey) # Now get surface points of original image to map to the centerlines dfe = ndi.distance_transform_cdt(oimg) points_toMap = np.array(np.nonzero(np.where(dfe==1,1,0))[::-1]).transpose().astype(np.int32) print("mapVoxelsToGraph") sg.mapVoxelsToGraph(points_toMap,ogkey, verbose=True) print("assignMappedPointsToPlanes") sg.assignMappedPointsToPlanes(ogkey) sg.saveCompressedGraphs(options.graph_file)
def makeDistanceTransform(self, method='edt'): """Create Distance transformed image Methods for the distance transform: - bf Brute force - cdt Checkerboard - edt Euclidean (default) """ if (method == 'edt'): self.imDistanceTransform = ndimage.distance_transform_edt( self._imSolidPore, sampling=self._spacing) elif (method == 'bf'): self.imDistanceTransform = ndimage.distance_transform_bf( self._imSolidPore, sampling=self._spacing) elif (method == 'cdt'): self.imDistanceTransform = ndimage.distance_transform_cdt( self._imSolidPore, sampling=self._spacing)
def label_image_ws(im, include_edge_regions=True): labels, num_labels = ndimage.measurements.label(im) dist = ndimage.distance_transform_edt(im) dist_taxicab = \ ndimage.distance_transform_cdt(im, metric='taxicab') im_new = np.copy(im) ### removal of structures at the image edge if not include_edge_regions: reg_max = find_reg_max_lone(dist, mask=im > 0) labelled_array_max, num_max = \ ndimage.measurements.label(reg_max, structure=morph.square(3)) labels_lone_ws = \ morph.watershed(-dist, markers=labelled_array_max, mask=im>0, connectivity=2, compactness=0.) list_edge = np.unique(np.concatenate( \ (labels_lone_ws[:1,:].flatten(), labels_lone_ws[-2:,:].flatten(), labels_lone_ws[:,:1].flatten(), labels_lone_ws[:,-2:].flatten()))) for l in list_edge: if l > 0: im_new[labels_lone_ws == l] = 0 dist[labels_lone_ws == l] = 0 dist_taxicab[labels_lone_ws == l] = 0 ### regional maxima are found and used as input for ### watershed segmentation reg_max = find_reg_max(dist, mask=im_new > 0) labelled_array_max, num_max = \ ndimage.measurements.label(reg_max, structure=[[0,0,0], [0,1,0], [0,0,0]]) labels_ws = morph.watershed(-dist, markers=labelled_array_max, mask=im_new > 0, connectivity=2, compactness=0.) return (labels_ws, dist, dist_taxicab, reg_max, num_max)
def selectSeedFromDFE(self): """For the current graph, set the root to be the node nearest the maximum DFE location. Uses a chamfer distance measure to save time""" try: dfe = self.dfe except: oimg = self.oimg self.dfe = ndi.distance_transform_cdt(oimg) dfe = self.dfe if( self.bifurcations[self.currentGraphKey] ): nds = np.array(self.bifurcations[self.currentGraphKey]) else: nds = np.array(self.cg.nodes()) if( nds.shape[0] == 1 ): # there is only one node to choose from so use it for seed return (nds[0,0],nds[0,1],nds[0,2]) vals = dfe[nds[:,2],nds[:,1],nds[:,0]] mi = vals.argmax() return (nds[mi,0],nds[mi,1],nds[mi,2])
def get_neighbours(self, array, index): ''' Get neighbour cells of the cell with given index in an array. @array: (numpy array) Array. @index: (int, int) Index of cell. @return: (numpy array) Array with the indices of neighbour cells. ''' matrix = np.array(array) indices = tuple(np.transpose(np.atleast_2d(index))) arr_shape = np.shape(matrix) dist = np.ones(arr_shape) dist[indices] = 0 dist = ndimage.distance_transform_cdt(dist, metric='chessboard') nb_indices = np.transpose(np.nonzero(dist == 1)) return [tuple(x) for x in nb_indices]
def mask2bounds(mask, width=2, n_classes=3): """ convert mask (with value range from 0 to n_classes-1) to bounds this operation is similar to gray2bounds """ h, w = mask.shape[:2] label_binary = label_binarize(mask.flatten(), classes=range(0, n_classes)) label_binary = np.reshape(label_binary, (h, w, -1)) bound_binary = np.zeros_like(label_binary) for i in range(n_classes): # number of classes before edge detection tmp = ndimage.distance_transform_cdt(label_binary[:, :, i], 'taxicab') cdt = np.logical_and(tmp >= 1, tmp <= width) bound_binary[:, :, i] = cdt bounds = np.any(bound_binary, axis=2).astype(np.uint8) return bounds
def edge_direction(edge_mask): """Given an edge mask, return the distance from each pixel to the mask, and the vector from each pixel to the nearest pixel in the mask. Parameter: edge_mask: boolean array that is True where image edges are. Returns: distances, nearest_edge distances: array same shape as edge_mask, containing the distance from every non-edge-mask pixel to the nearest pixel in the edge mask. nearest_edge: arary of shape (2,)+edge_mask.shape, containing the x and y coordinates of the vector from each non-edge pixel to the nearest edge pixel. """ distances, nearest_edge = ndimage.distance_transform_cdt( ~edge_mask, return_distances=True, return_indices=True) nearest_edge = nearest_edge - numpy.indices(edge_mask.shape) nearest_edge[:, edge_mask] = 0 return distances, nearest_edge
def edge_direction(edge_mask): """Given an edge mask, return the distance from each pixel to the mask, and the vector from each pixel to the nearest pixel in the mask. Parameter: edge_mask: boolean array that is True where image edges are. Returns: distances, nearest_edge distances: array same shape as edge_mask, containing the distance from every non-edge-mask pixel to the nearest pixel in the edge mask. nearest_edge: arary of shape (2,)+edge_mask.shape, containing the x and y coordinates of the vector from each non-edge pixel to the nearest edge pixel. """ distances, nearest_edge = ndimage.distance_transform_cdt(~edge_mask, return_distances=True, return_indices=True) nearest_edge = nearest_edge - numpy.indices(edge_mask.shape) nearest_edge[:, edge_mask] = 0 return distances, nearest_edge
def label_dilation(label, distance, metric='chessboard'): """ Dilate labeled area in label array by given distance (in pixels) A label cannot dilate over any other Input: label: a label array distance: a scalar indicating the euclidian distance metric: if 'chessbord', use chessbord distance if 'taxicab', use taxicap distance otherwise, use euclidian distance (slower) """ if metric in ('taxicab','chessboard'): dist, ind = _nd.distance_transform_cdt(label==0, return_indices=True,metric=metric) else: dist, ind = _nd.distance_transform_edt(label==0, return_indices=True) dil_label = label[tuple(ind)] dil_label[dist>distance] = 0 return dil_label
def _edge_map(image): """ Return a maps of edges suitable for visualization. Parameters ========== image: 2D array The image that the edges are extracted from. Returns ======== edge_mask: 2D masked array A mask of the edge as a masked array with parts without edges masked and the large extents detected with lower coefficients. """ edge_mask = _edge_detect(image)[-1] edge_mask = edge_mask.astype(np.float) edge_mask = -np.sqrt(ndimage.distance_transform_cdt(edge_mask)) edge_mask[edge_mask != 0] -= -.05 + edge_mask.min() edge_mask = np.ma.masked_less(edge_mask, .01) return edge_mask
def buildVessels(skel,skeldepth,convalue_n): global skel_dis mask_num = int(int(skel_dis.max()/MASK_RANGE)+1) rows,cols = skel.shape np.set_printoptions(threshold='nan') # print skel_dis struct = ndimage.generate_binary_structure(2, 1) for mask_index in range(0,mask_num): mask_thresh_h=MASK_RANGE*(mask_index+1) skel_mask=np.copy(skel) for i in range(0,rows): for j in range(0,cols): if skel_mask[i][j]>0 and skel_dis[i][j] >= mask_thresh_h: skel_mask[i][j]=0 if mask_index==0: skel_dilated=np.copy(skel) else: skel_mask=ndimage.binary_dilation(skel_mask,structure=struct,iterations=3) skel_dilated=np.logical_or(skel_dilated,skel_mask) # new_vessel=np.int8(skel_dilated) distance = ndimage.distance_transform_cdt(new_vessel , return_distances=True) skel_dis= skel * distance new_depth=updateDepth(new_vessel,skeldepth,convalue_n) new_depth=updateDepth(new_vessel,skeldepth,convalue_n,newdepth=new_depth) return new_vessel,new_depth
def _cv_signed_distance_from_zero_level(phi): return distance_transform_cdt(phi>0)-distance_transform_cdt(phi<=0)
table_corners = np.loadtxt("/home/joschu/comm/rope_hands/once/table_corners.txt") z_ax = np.cross(table_corners[1] - table_corners[0], table_corners[2]-table_corners[1]) z_ax *= -np.sign(z_ax[2]) height = (xyz * z_ax[None,None,:]).sum(axis=2) M,N = height.shape #mip.initialize() #mip.put(height,"height") #mip.eval("addpath('~/python/jds_image_proc')") #mip.eval("height1 = inpaint_nans(height);") #height1 = mip.get("height1") labels = cv2.imread('/home/joschu/comm/rope_hands/labels/data000000000000.png')[:,:,0] rope = (labels==1).copy() height1 = ndi.distance_transform_cdt(rope,return_distances=True,return_indices=False).astype('float32') d0 = ndi.gaussian_filter1d(height1,sigma=3,axis=0,order=1) d1 = ndi.gaussian_filter1d(height1,sigma=3,axis=1,order=1) d00 = ndi.gaussian_filter1d(d0,sigma=3,axis=0,order=1) d01 = ndi.gaussian_filter1d(d0,sigma=3,axis=1,order=1) d11 = ndi.gaussian_filter1d(d1,sigma=3,axis=1,order=1) D1 = np.empty((M,N,2)) D1[:,:,0] = d0 D1[:,:,1] = d1 D2 = np.empty((M,N,2,2)) D2[:,:,0,0] = d00 D2[:,:,0,1] = d01
from sliceOrientation import OrientMask import imageTools.ITKUtils.io as io import scipy.ndimage as ndi import numpy as na import pickle fle=open("PE00001NonEndpoints.pckle",'wb') output2=open("PE00001NeighborsNonPoints7x7.pckle", 'wb') img=io.readImage("PE00001Filter0_seg.mha", returnITK=False, imgMode="uchar") #Must create the mask so we can identify the points that are not endpoints mask=na.where(img>0, 1, 0) point=nxvasc.nxvasc() point.setMask(mask) point.createMaskDictionary() point.get7x7matrix() f1=ndi.distance_transform_cdt(img) surface=na.where(f1==1,1,0) indsSurface =na.nonzero(surface.flat==1)[0] length=len(indsSurface) print("length",length) ModifiedSampledPoints=[] ModifiedPoints=[] points=[] for i in indsSurface: if len(ModifiedPoints)<112: crds=point.get_crds(i) print(crds) #get the neighbors to add up the neighborhood neighbor = mask[crds[2]-3:crds[2]+4,crds[1]-3:crds[1]+4,crds[0]-3:crds[0]+4] if len(neighbor)<7: pass