def getParams(self): img = self.ch1 hist, bins = np.histogram(img.ravel(), 256, [0, np.max(img)]) #plt.hist(img.ravel(),256,[0,np.max(img)]); plt.show() zero = np.argmax(hist) img = img - bins[zero] im = np.abs(img) threshold = threshold_isodata(im) im = im > threshold filled = binary_fill_holes(im).astype(int) filled = binary_closing(filled) A1 = np.count_nonzero(filled) P1 = perimeter(filled, neighbourhood=16) C1 = 4 * 3.14 * A1 / (P1 * P1) img = self.ch6 hist, bins = np.histogram(img.ravel(), 256, [0, np.max(img)]) #plt.hist(img.ravel(),256,[0,np.max(img)]); plt.show() zero = np.argmax(hist) img = img - bins[zero] im = np.abs(img) threshold = threshold_isodata(im) im = im > threshold filled = binary_fill_holes(im).astype(int) filled = binary_closing(filled) A2 = np.count_nonzero(filled) P2 = perimeter(filled, neighbourhood=16) C2 = 4 * 3.14 * A2 / (P2 * P2) params = np.array([A1, P1, C1, A2, P2, C2]) return params
def cluster_process(labels, original, activations): rbase = np.zeros(labels.shape) rubase = np.zeros(labels.shape) rubase[range(0,20),:] = 1 rubase[:,range(0,20)] = 1 rubase[range(-20,-1),:] = 1 rubase[:,range(-20,-1)] = 1 for i in range(1, int(np.max(labels))+1): base = np.zeros(labels.shape) base[labels==i] = 1 li = len(base.nonzero()[0]) if li>0: hull = convex_hull_image(base) lh =len(hull.nonzero()[0]) sel_org = base*original sel_act = base*activations cond = (li > 4000 and float(lh) / float(li) < 1.07 and perimeter(base)**2.0 / li < 30) or np.max(base * rubase) > 0.5 # print li>4000 and float(lh)/float(li)<1.07, perimeter(base)**2.0/li<30, np.max(base*rubase)>0.5, np.min(original[base>0]) hard_array =[li > 4000, float(lh) / float(li) < 1.07] optional_array = [perimeter(base)**2.0/li < 25, np.percentile(sel_org[sel_org>0], 5) > 0.2, np.percentile(sel_act, 90) - np.percentile(sel_act, 90)] print hard_array, optional_array if debug and li>1000: rs(base,'subspread cluster') if cond: rbase = rbase + base rbase[rubase.astype(np.bool)] = 1 return dilation(rbase, selem)
def peri_area_series(self, levels): perimeters = np.zeros(len(levels)-1) areas = np.zeros(len(levels)-1) for i, level in enumerate(levels): mask_image = np.ma.masked_inside(self.data,levels[i],levels[i+1]) mask_image_outer = np.ma.masked_greater_equal(self.data,levels[i]) mask_image_inner = np.ma.masked_greater_equal(self.data,levels[i+1]) perimeters.append((perimeter(mask_image_outer.mask)+perimeter(mask_image_inner.mask))) areas.append((self.__len__-np.nansum(mask_image.mask))) self.areas = areas self.perimeters = perimeters
def ComputePerimeter(binarizedImage): perim = measure.perimeter(binarizedImage) print('Perimeter calculation complete >>') print('Perimeter is:', perim, 'pixels.') print('Dimensions of preimeter variable is:', perim.shape) print('Perimeter Type:', type(perim)) return perim
def give_Aver(self, srt, name): filename = os.path.join(skimage.data_dir, srt + name) image = io.imread(filename) image_g = rgb2gray(image) edges = feature.canny(image_g, sigma=self.sigma) aver = measure.perimeter(edges) return aver
def compute_blocky_metric(mtx, kernel_size, sd_thresh, remove_size): ''' Compute perimeter of all connected components for an input matrix after uniform smoothing, Z-standardization, and cleaning for small components. input: mtx - n * n matrix kernel_size - size of kernel used in smoothing sd_thresh - threshold to use for binarization remove_size - filter on number of cells required in connected components output: dict of all intermediary quantities (standardized matrix, binarized matrix, cleaned matrix) and the perimeter of the clean matrix. ''' mtx_smooth = smooth(Z, kernel_size) Z = standardize(mtx_smooth) Z_threshold = binarize(Z, sd_thresh) labels = measure.label(Z_threshold) Z_clean = remove_small_clusters(Z_threshold, labels, remove_size) blockyness = measure.perimeter(Z_clean, neighbourhood=4) ## prepare output dict out = {} out['mtx_standardize'] = Z out['mtx_binarized'] = Z_threshold out['mtx_clean'] = Z_clean out['perimeter'] = blockyness return(out)
def shape_measures(image): """Returns features about the 'basic' shape measures: * scaled area * Solidity * Extend * Major and minor axes lengths * Centroid displacement Look at 'http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops' for more informations about these measures.""" # make image binary new_im = image new_im[new_im > 0] = 1 per = perimeter(new_im) lbs = label(new_im) properties = regionprops(lbs) # extract properties of interest if len(properties) > 0: ratio = properties[0].area / (per * per) # scaled area solidity = properties[0].solidity extent = properties[0].extent major_axis_scaled = properties[0].major_axis_length / per minor_axis_scaled = properties[0].minor_axis_length / per else: ratio = 0 solidity = 0 extent = 0 major_axis_scaled = 0 minor_axis_scaled = 0 return [ratio, solidity, extent, major_axis_scaled, minor_axis_scaled]
def perimeter(self): """ The perimeter of the source segment, approximated lines through the centers of the border pixels using a 4-connectivity. """ from skimage.measure import perimeter return perimeter(self._cutout_segment_bool, 4) * u.pix
def getChar(self): if not self.isPrepared: self.preparerMedian() print(u'Image en préparation automatique, attention aux paramètres') self.char['taux'] = 100*np.sum(self.ready)/float(self.size) self.char['temp'],self.char['time'] = finddata(self.filename) self.char['perimeter']=measure.perimeter(self.ready)
def perimeter(self): """ The perimeter of the source segment, approximated lines through the centers of the border pixels using a 4-connectivity. """ from skimage.measure import perimeter return perimeter(self._cutout_segment_bool, 4) * u.pix
def batch_loss_perim(y_batch, p_batch): print 'blp' m = float(y_batch.shape[0]) bce_loss = sum(bce(y, p) for (y, p) in zip(y_batch, p_batch)) / m perim_loss = sum( perimeter(np.round(p)) / np.count_nonzero(np.round(p)) for p in p_batch) / m return bce_loss + perim_loss
def circularity(spot, area): if not area: return 0 perim = perimeter(spot) if perim != 0: return (4 * np.pi * area) / (perim * perim) return 0
def measure(self, img, m_type: int) -> float: mask = img.get_mask(m_type) mask_one = mask / mask.max() label_img = label(mask_one) region = regionprops(label_img) area = region[0].area per = perimeter(mask_one) value = (4 * math.pi * area) / (per**2) return value
def extractFeature(name, showall, showbb, flag): (img, regions, ax, rthre, cthre) = extractImage(name, showall, showbb, flag) Features = [] boxes = [] for props in regions: tmp = [] minr, minc, maxr, maxc = props.bbox if maxc - minc < cthre or maxr - minr < rthre or maxc - minc > cthre * 9 or maxr - minr > rthre * 9: continue tmp.append(minr) tmp.append(minc) tmp.append(maxr) tmp.append(maxc) boxes.append(tmp) if showbb == 1: ax.add_patch( Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=1)) # computing hu moments and removing small components roi = img[minr:maxr, minc:maxc] m = moments(roi) cr = m[0, 1] / m[0, 0] cc = m[1, 0] / m[0, 0] mu = moments_central(roi, cr, cc) nu = moments_normalized(mu) hu = moments_hu(nu) area = (maxr - minr) * (maxc - minc) # add convexity p = perimeter(img[minr:maxr, minc:maxc]) con = (area / (p * p)) * 4 * math.pi convex = np.array([con]) hu = np.concatenate((hu, convex)) # add density den = area / float(props.convex_area) dense = np.array([den]) hu = np.concatenate((hu, dense)) Features.append(hu) # print boxes plt.title('Bounding Boxes') if showbb == 1: io.show() return Features, boxes,
def perimeter_calculation(label_mask): perimeter_val=[] for slice in range(label_mask.shape[-1]): perimeter_val.append(perimeter(label_mask[:,:,slice])) average_perimeter = np.sum(perimeter_val)/label_mask.shape[-1] return average_perimeter
def main(): data = bf.load_image("test2.h5") thres = np.quantile(data.ravel(), 0.65) bindata = data // thres op_selem = disk(6) close_selem = disk(12) opened = opening(bindata, op_selem) closed = closing(opened, close_selem) peri = perimeter(closed) area = np.count_nonzero(closed == 1) compact = 4 * np.pi * area / (peri**2) print(peri, area, compact) bf.show_images([data, bindata, opened, closed, canny(closed)])
def perimeter(mask, invert=False): ''' Calculate total perimeter of all objects in binary image. calculates the perimeter of binary 2D shapes if background is white and the region of interest black, invert should be True. Parameters ---------- mask : array_like binary image ''' if invert: zeroidx = mask == 0 onesidx = mask == 255 maskinvert = np.copy(mask) maskinvert[zeroidx] = 255 maskinvert[onesidx] = 0 return measure.perimeter(maskinvert > 110) else: return measure.perimeter(mask > 110)
def get_perimeter(img): """ 1. Import the image: "as_gray=True" is needed to reshape the original 3D array to a 2D array. The perimeter function only accepts 2D arrays. 2. Invert the grayscale. I did this because the standard grayscale image gave me a value of 0.0 """ img = io.imread('Rothko_AI/' + img, as_gray=True) img = invert(img) return perimeter(img, neighbourhood=4)
def imageFeatures(s): tmparr = s.pixel_array threshold_mask = tmparr > 800 tmpmask = ndimage.binary_erosion(threshold_mask, iterations=6) closedmask = ndimage.binary_fill_holes(tmpmask) n_pixels = np.sum(tmpmask) nf_pixels = np.sum(closedmask) ## # pixels above threshold v_pixel = s.PixelSpacing[0] * s.PixelSpacing[1] * s.SliceThickness * 10**( -6) # volume 1 pixel in leters size = nf_pixels * v_pixel size_hollow = n_pixels * v_pixel perimeter = measure.perimeter(closedmask) * s.PixelSpacing[0] meanhu = np.mean(tmparr[closedmask]) return [size, size_hollow, perimeter, meanhu]
def get_shape_analysis(data, show_plot): # returns shape analysis features and plots thres = np.quantile(data.ravel(), 0.65) bindata = data // thres op_selem = disk(6) close_selem = disk(12) opened = opening(bindata, op_selem) closed = closing(opened, close_selem) peri = perimeter(closed) area = np.count_nonzero(closed == 1) compact = (peri**2) / (4 * np.pi * area) if show_plot: bf.show_images([data, bindata, opened, closed, canny(closed)]) return ([peri, area, compact])
def circularThresholdLabels(labelImg, circularRange): particleList = numpy.unique(labelImg[1:]) for particle in particleList: bImgLabelN = labelImg==particle circularity = 0 area = bImgLabelN.sum() perimeter = measure.perimeter(bImgLabelN) if (perimeter>0): circularity = (4*numpy.pi*area)/(perimeter**2) if (circularity>1): circularity=1/circularity if not(circularity>=circularRange[0] and circularity<=circularRange[1]): labelImg[bImgLabelN]=0 return labelImg
def circularity(I): """ Circularity criterion 4*pi*A/P**2 returns crofton and classic """ P = perimCrofton(I) print("Perimeter by crofton: ", P) A = np.sum(I) C = np.pi*4*A/P**2 p = measure.perimeter(I, neighbourhood=4) print("Usual perimeter: ", p) c = np.pi*4*A/p**2 return C, c
def get_sub_compacity(self, sub_images): compacities = [] for index in range(len(sub_images)): compacities.append([]) for index2, im in enumerate(sub_images[index]): #contour = measure.find_contours(im, level=0.8) #print(contour) #exit(0) perimeter = measure.perimeter(im, neighbourhood=4) area = np.count_nonzero(im) compacity = perimeter**2 / area if compacity < 4 * np.pi: print("Compacity is too small {} < {}".format( compacity, 4 * np.pi)) compacity = 100 #print("{}.{}:".format(index, index2), perimeter, area, compacity) compacities[index].append(compacity) return compacities
def minkoMeasured(G, sigma, hmin, hmax): H = np.arange(hmin, hmax, .1) A = [] P = [] E = [] bar = progressbar.ProgressBar() for h in bar(H): levelset = G >= h # A[i] = np.sum(levelset); # P[i] = measure.perimeter(levelset);# perimeter in 4-neighborhood # E[i] = eulerNb4(levelset) # euler number a, p, e = bwminko(levelset) p = measure.perimeter(levelset) A.append(a) P.append(p) E.append(e) return A, P, E
def _extract_features(self, labels, intensity): self.ndim = labels.ndim self.spacing = np.broadcast_to(np.array(self.spacing), self.ndim) self.isotropic = np.all(self.spacing == self.spacing[0]) # map 2D feature names if 3D image if self.ndim == 3: # skimage regions props uses 2D feature names (e.g. perimeter, area instead of surface, volume respectively) features = { self._name_mapping_3D_2D.get(f, f) for f in self.features } else: features = self.features # special case pre: extract "convex_image" to compute missing "convex_perimeter" feature if 'convex_perimeter' in features: features = [ 'convex_image' if x == 'convex_perimeter' else x for x in features ] # extract actual features props = regionprops_table(labels, intensity_image=intensity, properties=features, separator='-') # special case post: extract compute missing "convex_perimeter" feature convex_images = props.pop('convex_image', None) if convex_images is not None: props['convex_perimeter'] = [ perimeter(hull) for hull in convex_images ] # map back 3D feature names if 3D image if self.ndim == 3: props = { self._name_mapping_2D_3D.get(key, key): val for key, val in props.items() } return props
def relperimeterthresh(image, exponent = 2): try: #Lowering the exponent increases tolerance for rough image edges, and is more suitable when #there is a large variance in foreground brightness lothresh = filters.threshold_triangle(image) hithresh = filters.threshold_otsu(image) if lothresh > hithresh: lothresh = hithresh // 2 threshqual = [] threshsearch = [] for thresh in range(lothresh, hithresh +10, max((hithresh-lothresh)//5, 1)): sample = image > thresh threshqual.append((measure.perimeter(sample) ** exponent)/np.sum(sample)) threshsearch.append(thresh) goodthresh = threshsearch[np.argmin(threshqual)] return goodthresh except: try: return filters.threshold_otsu(image) except ValueError: return np.nan
def selective_search(im_orig, scale=40.0, sigma=0.8, min_size=40, gp=[0.5, 0.5]): '''Selective Search Parameters ---------- im_orig : ndarray Input image scale : int Free parameter. Higher means larger clusters in felzenszwalb segmentation. sigma : float Width of Gaussian kernel for felzenszwalb segmentation. min_size : int Minimum component size for felzenszwalb segmentation. Returns ------- img : ndarray image with region label region label is stored in the 4th value of each pixel [r,g,b,(region)] regions : array of dict [ { 'rect': (left, top, width, height), 'labels': [...], 'size': component_size }, ... ] ''' assert im_orig.shape[2] == 3, "3ch image is expected" # load image and get smallest regions # region label is stored in the 4th value of each pixel [r,g,b,(region)] img = _generate_segments(im_orig, scale, sigma, min_size) if img is None: return None, {} imsize = img.shape[0] * img.shape[1] R = _extract_regions(img) # extract neighbouring information neighbours = _extract_neighbours(R) # calculate initial similarities S = {} for (ai, ar), (bi, br) in neighbours: S[(ai, bi)] = _calc_sim(ar, br, imsize) # hierarchal search while S != {}: # get highest similarity i, j = sorted(S.items(), key=lambda i: i[1])[-1][0] # merge corresponding regions t = max(R.keys()) + 1.0 R[t] = _merge_regions(R[i], R[j]) # mark similarities for regions to be removed key_to_delete = [] for k, v in list(S.items()): if (i in k) or (j in k): key_to_delete.append(k) # remove old similarities of related regions for k in key_to_delete: del S[k] # calculate similarity set with the new region for k in [a for a in key_to_delete if a != (i, j)]: n = k[1] if k[0] in (i, j) else k[0] S[(t, n)] = _calc_sim(R[t], R[n], imsize) regions = [] gp[0] = gp[0] * img.shape[1] gp[1] = gp[1] * img.shape[0] for k, r in list(R.items()): # x is width width = r['max_x'] - r['min_x'] height = r['max_y'] - r['min_y'] if (gp[0]>r['min_x']-0.25*width) and \ (gp[1]>r['min_y']-0.25*height) and \ (gp[0]<r['max_x']+width*0.25) and \ (gp[1]<r['max_y']+height*0.25): regions.append({ 'rect': (r['min_x'], r['min_y'], r['max_x'] - r['min_x'], r['max_y'] - r['min_y']), 'd': math.sqrt((gp[0] - (r['min_x'] + r['max_x']) / 2)**2 + (gp[1] - (r['min_y'] + r['max_y']) / 2)**2), 'size': r['size'], 'labels': r['labels'], 'masks': r['masks'], 'hist_c': r['hist_c'], 'hist_t': r['hist_t'], 'objectness': perimeter(r['masks']) / (regionprops(r['masks'].astype( numpy.uint8))[0].major_axis_length + regionprops( r['masks'].astype(numpy.uint8))[0].minor_axis_length), }) return regions
date1 = str(year)+'-01-01T00:00:00' date2 = str(year)+'-12-31T23:00:00' it_tot = index_date(MSEAtl.time,date1)[0] Nt = MSEAtl.time.sel({'time':slice(date1,date2)}).shape[0] L_CONTOUR[str(year)] = np.zeros((Nt,)) for it in range(Nt): print('it=',it,' & it_tot=',it_tot,' ',end='\r') MSE_tmp = MSEAtl[it_tot,:,:] # Contour = curve.get_contours(MSE_tmp>np.percentile(MSE_tmp,80)) # L = 0 # for j,contour in enumerate(Contour): # plt.plot(lonAtl[contour[:,1].astype(int)],latAtl[contour[:,0].astype(int)],color='k') # L += np.sum(contour*dx) MSE_binary = np.zeros(np.shape(MSE_tmp)) MSE_binary[MSE_tmp>np.percentile(MSE_tmp, per_thresh)] = 1 binary_boundary=np.copy(MSE_binary) binary_boundary[:,1:-1]=0 L = dx*(measure.perimeter(MSE_binary,8)- np.sum(binary_boundary)) L_CONTOUR[str(year)][it] = L it_tot+=1 #### Save the contour length in a pickle file path_PKL = '/users/jwindmil/2019_WMI/dev/jwindmiller/PKL_DATA/' hf = open(path_PKL+'10_2_CONTOURL_%i'%(per_thresh)+str(year)+'.pkl','wb') CONdata = {"Tot_Contour_km":L_CONTOUR,"time":MSEAtl.time} pickle.dump(CONdata,hf) hf.close()
im_crop = get_roi(bw_img) dist_map = get_roi(bw_dmap) node_id_image = get_roi(ws_labels) ax1.imshow(im_crop) node_dict = {} for c_node in np.unique(node_id_image[node_id_image > 0]): y_n, x_n = np.where(node_id_image == c_node) node_dict[c_node] = { "x": np.mean(x_n), "y": np.mean(y_n), "width": np.mean(dist_map[node_id_image == c_node]), "perimeter": perimeter(node_id_image == c_node), } ax1.plot(np.mean(x_n), np.mean(y_n), "rs") edge_dict = {} for i in node_dict.keys(): i_grow = dilation(node_id_image == i, np.ones((3, 3))) for j in node_dict.keys(): if i < j: j_grow = dilation(node_id_image == j, np.ones((3, 3))) interface_length = np.sum(i_grow & j_grow) if interface_length > 0: v_nodes = [i, j] edge_dict[(i, j)] = {
def get_ratio_properties(self, smallest_size, theMask, ratio_intensity, threshold, Img_after, i, j): # remove artifacts connected to image border self.Labelmask = theMask self.ratioImag = ratio_intensity self.row_num = i self.column_num = j self.threshold = threshold self.originimg = Img_after cleared = self.Labelmask.copy() clear_border(cleared) # label image regions label_image = label(cleared) #image_label_overlay = label2rgb(label_image, image=image) #fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6)) #ax.imshow(label_image) #contours = find_contours(original_intensity, self.threshold) dtype = [('Row index', 'i4'), ('Column index', 'i4'), ('Mean intensity', float), ('Circularity', float), ('Mean intensity in contour', float)] region_mean_intensity_list = [] region_circularit_list = [] region_meanintensity_contour_list = [] loopmun = 0 dirforcellprp = {} for region in regionprops(label_image, intensity_image=self.ratioImag): # skip small images if region.area > smallest_size: # draw rectangle around segmented coins #minr, minc, maxr, maxc = region.bbox #rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2) #ax.add_patch(rect) #centroidint1 = int(region.centroid[0]) #centroidint2 = int(region.centroid[1]) #ax.text(centroidint1+50, centroidint2+55, round(region.mean_intensity,3),fontsize=15, style='italic',bbox={'facecolor':'red', 'alpha':0.5, 'pad':10}) region_mean_intensity = region.mean_intensity #mean intensity of the region, 0 pixels are omitted. #allpixelnum = region.bbox_area #labeledpixelnum = region.area #number of pixels in region omitting 0. filledimg = region.filled_image filledperimeter = perimeter(filledimg) #Sliced_binary_region_image = region.image intensityimage = region.intensity_image singlethresh = threshold_otsu(filledimg) #print(region.area) #print(region.bbox_area) #print(region_mean_intensity) s = imageanalysistoolbox() contourimage = s.contour(filledimg, intensityimage, singlethresh) self.contour_mask = s.inwarddilationmask( contourimage, filledimg, 3) filledimg = region.filled_image #Binary region image with filled holes which has the same size as bounding box. filledperimeter = perimeter(filledimg) regioncircularity = (4 * math.pi * region.filled_area) / ( filledperimeter * filledperimeter ) # region.perimeter will count in perimeters from the holes inside self.contour_origin_image = self.contour_mask * intensityimage contourprops = regionprops(self.contour_mask, intensityimage) contour_mean = contourprops[0].mean_intensity #print('contour_mean:'+str(contour_mean)) #print(region_mean_intensity) region_mean_intensity_list.append(region_mean_intensity) region_circularit_list.append(regioncircularity) region_meanintensity_contour_list.append(contour_mean) dirforcellprp[loopmun] = (self.row_num, self.column_num, region_mean_intensity, regioncircularity, contour_mean) loopmun = loopmun + 1 cell_properties = np.zeros(len(region_mean_intensity_list), dtype=dtype) for p in range(loopmun): cell_properties[p] = dirforcellprp[p] return region_mean_intensity_list, cell_properties, self.contour_origin_image
dapi=pixels[0,:,:] plt.imshow(dapi) GFP=pixels[1,:,:] plt.imshow(GFP) block_size = 21 nmask = threshold_local(dapi, block_size,offset=0.0004) nmask2 = dapi > nmask plt.imshow(nmask2) nmask3 = binary_opening(nmask2, structure=np.ones((3,3))).astype(np.float64) plt.imshow(nmask3) nmask4 = binary_fill_holes(nmask3) plt.imshow(nmask4) perimeter(nmask4, neighbourhood=4) all_labels = measure.label(nmask4) plt.imshow(all_labels) label_objects, nb_labels = label(all_labels) plt.imshow(label_objects) sizes = np.bincount(label_objects.ravel()) #np.histogram(sizes, bins=10, range=None) #plt.hist(sizes, bins='auto') #plt.show() mask_sizes = sizes > 250 #all the values larger than 250 is True mask_sizes[0] = 0 #column 0, False will get the value of zero gsegg = mask_sizes[label_objects] gsegg, nb_labels = label(gsegg) plt.imshow(gsegg)
def get_cell_dictionary(self, smallest_size, theMask, threshold, intensity_bef, intensty_aft, i, j, contour_thres, contour_dilationparameter): # remove artifacts connected to image border self.Labelmask = theMask self.Imagbef = intensity_bef self.Imageaft = intensty_aft self.row_num = i self.column_num = j self.threshold = threshold self.contour_thres = contour_thres self.contour_dilationparameter = contour_dilationparameter cleared = self.Labelmask.copy() clear_border(cleared) # label image regions label_image = label(cleared) self.individual_cell_dic_bef = {} self.individual_cell_dic_aft = {} loopmun = 0 for region in regionprops(label_image, intensity_image=self.Imagbef ): # USE image before perfusion as template # skip small images if region.area > smallest_size: # draw rectangle around segmented coins minr, minc, maxr, maxc = region.bbox region_mean_intensity = region.mean_intensity #mean intensity of the region, 0 pixels in label are omitted. #allpixelnum = region.bbox_area #labeledpixelnum = region.area #number of pixels in region omitting 0. filledimg = region.filled_image filledperimeter = perimeter(filledimg) #Sliced_binary_region_image = region.image self.intensityimage_intensity = region.intensity_image # need a copy of this cause region will be altered by s.contour #self.regionimage_before = self.intensityimage_intensity.copy() #self.regionimage_after = self.Imageaft[minr:maxr, minc:maxc] #Get 2 more pixels out of boundary box in case of cell movements #We need to add 2 rows and columns of 0 to the whole FOV in case cells detected at the edge expanded_image_container_bef = np.zeros( (self.Imagbef.shape[0] + 4, self.Imagbef.shape[1] + 4)) expanded_image_container_bef[2:self.Imagbef.shape[0] + 2, 2:self.Imagbef.shape[1] + 2] = self.Imagbef expanded_image_container_aft = np.zeros( (self.Imageaft.shape[0] + 4, self.Imageaft.shape[1] + 4)) expanded_image_container_aft[2:self.Imageaft.shape[0] + 2, 2:self.Imageaft.shape[1] + 2] = self.Imageaft self.regionimage_before = expanded_image_container_bef[minr - 2:maxr + 2, minc - 2:maxc + 2] self.regionimage_after = expanded_image_container_aft[minr - 2:maxr + 2, minc - 2:maxc + 2] self.regionimage_before_for_contour = self.regionimage_before.copy( ) self.regionimage_after_for_contour = self.regionimage_after.copy( ) self.individual_cell_dic_bef[str( loopmun )] = self.regionimage_before_for_contour # put each cell region into a dictionary self.individual_cell_dic_aft[str( loopmun)] = self.regionimage_after_for_contour loopmun = loopmun + 1 return self.individual_cell_dic_bef, self.individual_cell_dic_aft
def compactness(labelled, label): return 4 * np.pi * np.sum(labelled == label) / (perimeter( labelled == label)**2)
# EXTRACAO DE CARACTERISTICAS f_1 = [0, 0, 0] f_2 = [0, 0, 0] img_1 = np.divide(img_1, 255.0) img_2 = np.divide(img_2, 255.0) prop1 = img_1.shape[0]*img_1.shape[1] prop2 = img_2.shape[0]*img_2.shape[1] # AREAS f_1[0] = np.sum(img_1)/prop1 f_2[0] = np.sum(img_2)/prop2 # PERIMETROS f_1[1] = perimeter(img_1)/prop1 f_2[1] = perimeter(img_2)/prop2 f_1[2] = dist_1/prop1 f_2[2] = dist_2/prop2 person = pearsonr(f_1, f_2) dist = (distance.euclidean(f_1, f_2))*100 print np.abs((person[0]*100)-dist) plt.subplot(121), plt.imshow(img_1, cmap='gray') plt.title(''), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(img_2, cmap='gray') plt.title(''), plt.xticks([]), plt.yticks([])
def morphologyStats(image, res): perim = (float(perimeter(image)) / res) * (2.0 + 35.0/64.0) area = (float(np.sum(image != 0)) / (res**2)) * ((2.0 + 35.0/64.0)**2) dissection = (4 * area) / (perim ** 2) compactness = (perim ** 2) / area return (perim, area, dissection, compactness)