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
def cell_processing(self, individual_cell_bef, individual_cell_aft): self.regionimage_before_individualcell = individual_cell_bef self.regionimage_after_individualcell = individual_cell_aft self.cell_openingfactor = 1 self.cell_closingfactor = 5 # Get binary cell image baseed on expanded current region image thresh_regionbef = threshold_otsu( self.regionimage_before_individualcell) self.expanded_binary_region_bef = np.where( self.regionimage_before_individualcell >= thresh_regionbef, 1, 0) binarymask_bef = opening(self.expanded_binary_region_bef, square(self.cell_openingfactor)) self.expanded_binary_region_bef = closing( binarymask_bef, square(self.cell_closingfactor)) thresh_regionaft = threshold_otsu( self.regionimage_after_individualcell) self.expanded_binary_region_aft = np.where( self.regionimage_after_individualcell >= thresh_regionaft, 1, 0) binarymask_aft = opening(self.expanded_binary_region_aft, square(self.cell_openingfactor)) self.expanded_binary_region_aft = closing( binarymask_aft, square(self.cell_closingfactor)) plt.figure() plt.imshow(self.expanded_binary_region_bef, cmap=plt.cm.gray) plt.show() seed = np.copy(self.expanded_binary_region_bef) seed[1:-1, 1:-1] = self.expanded_binary_region_bef.max() mask = self.expanded_binary_region_bef filled = reconstruction(seed, mask, method='erosion') plt.figure() plt.imshow(filled, cmap=plt.cm.gray) plt.show() # Get contour here is kind of redundant s = imageanalysistoolbox() contour_mask_bef = s.contour( self.expanded_binary_region_bef, self.regionimage_before_individualcell.copy(), self.contour_thres ) # after here self.intensityimage_intensity is changed from contour labeled with number 5 to binary image contour_mask_of_intensity_bef = s.inwarddilationmask( contour_mask_bef, self.expanded_binary_region_bef, self.contour_dilationparameter) contourimage_intensity_aft = s.contour( self.expanded_binary_region_aft, self.regionimage_after_individualcell.copy(), self.contour_thres ) # after here self.intensityimage_intensity is changed with contour labeled with number 5 contour_mask_of_intensity_aft = s.inwarddilationmask( contourimage_intensity_aft, self.expanded_binary_region_aft, self.contour_dilationparameter) plt.figure() #plt.imshow(contour_mask_of_intensity_bef, cmap = plt.cm.gray) plt.imshow(self.regionimage_before_individualcell, cmap=plt.cm.gray) plt.show() cleared = self.expanded_binary_region_bef.copy( ) # Necessary for region iteration clear_border(cleared) label_image = label(cleared) for sub_region in regionprops(label_image, self.regionimage_before_individualcell): if sub_region.area < 3: #int(np.size(self.regionimage_before_individualcell)*0.1): for i in range(len(sub_region.coords)): #print(sub_region.coords[i]) contour_mask_of_intensity_bef[sub_region.coords[i][0], sub_region.coords[i][1]] = 0 cleared_1 = self.expanded_binary_region_aft.copy() clear_border(cleared_1) label_image_aft = label(cleared_1) for sub_region_aft in regionprops( label_image_aft, self.regionimage_after_individualcell): if sub_region_aft.area < 3: #int(np.size(self.regionimage_after_individualcell)*0.1): for j in range(len(sub_region_aft.coords)): #print(sub_region_aft.coords[j]) contour_mask_of_intensity_aft[ sub_region_aft.coords[j][0], sub_region_aft.coords[j][1]] = 0 plt.figure() plt.imshow(contour_mask_of_intensity_bef, cmap=plt.cm.gray) plt.show()
def get_cell_properties_Roundstack(self, imagestack, RegionProposalMask, smallest_size, contour_thres, contour_dilationparameter, cell_region_opening_factor, cell_region_closing_factor): cleared = RegionProposalMask.copy() clear_border(cleared) # label image regions, prepare for regionprops label_image = label(cleared) dtype = [('Mean intensity', float), ('Mean intensity in contour', float), ('Circularity', float), ('Contour soma ratio', float)] CellPropDictEachRound = {} for EachRound in range(len(imagestack)): region_mean_intensity_list = [] region_circularit_list = [] region_meanintensity_contour_list = [] RegionLoopNumber = 0 dirforcellprp={} if EachRound == 0: # Plot the label figure in the first round. plt.figure() self.fig_showlabel, self.ax_showlabel = plt.subplots(ncols=1, nrows=1, figsize=(6, 6)) self.ax_showlabel.imshow(imagestack[0])#Show the first image for region in regionprops(label_image,intensity_image = imagestack[0]): # USE first image in stack 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) regioncircularity = (4 * math.pi * region.filled_area) / (filledperimeter * filledperimeter) # region.perimeter will count in perimeters from the holes inside #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 # Based on the boundingbox for each cell from first image in the stack, raw image of slightly larger region is extracted from each round. self.RawRegionImg = imagestack[EachRound][max(minr-4,0):min(maxr+4, imagestack[0].shape[0]), max(minc-4,0):min(maxc+4, imagestack[0].shape[0])] # Raw region image self.RawRegionImg_for_contour = self.RawRegionImg.copy() #---------Get the cell filled mask------------- self.filled_mask_bef = imageanalysistoolbox.get_cell_filled_mask(RawRegionImg = self.RawRegionImg, region_area = region.area, cell_region_opening_factor = cell_region_opening_factor, cell_region_closing_factor = cell_region_closing_factor) filled_origin_image_intensity = self.RawRegionImg*self.filled_mask_bef # Intensity image of cell with hole filled filled_mean_bef = np.mean(self.RawRegionImg[np.where(self.filled_mask_bef == 1)]) # Mean pixel value of filled raw cell area self.filled_mask_convolve2d = imageanalysistoolbox.smoothing_filled_mask(self.RawRegionImg, filled_mask_bef = self.filled_mask_bef, region_area = region.area) # Find contour along filled image imageanalysistoolbox_instacne=imageanalysistoolbox() contour_mask_bef = imageanalysistoolbox_instacne.contour(self.filled_mask_convolve2d, self.RawRegionImg_for_contour.copy(), contour_thres) # after here self.intensityimage_intensity is changed from contour labeled with number 5 to binary image self.contour_mask_of_cell = imageanalysistoolbox_instacne.inwarddilationmask(contour_mask_bef ,self.filled_mask_bef, contour_dilationparameter) # contourimage_intensity_aft = s.contour(self.filled_mask_aft, self.regionimage_after_for_contour.copy(), self.contour_thres) # after here self.intensityimage_intensity is changed with contour labeled with number 5 # self.contour_mask_of_intensity_aft = s.inwarddilationmask(contourimage_intensity_aft ,self.filled_mask_aft, self.contour_dilationparameter) contour_mean_bef = np.mean(self.RawRegionImg[np.where(self.contour_mask_of_cell == 1)]) # contour_mean_aft = np.mean(self.regionimage_after[np.where(self.contour_mask_of_intensity_aft == 1)]) self.cell_soma_mask_bef = self.filled_mask_bef - self.contour_mask_of_cell contour_origin_image_intensity = self.RawRegionImg*self.contour_mask_of_cell # Intensity image of cell contour soma_origin_image_intensity = self.RawRegionImg*self.cell_soma_mask_bef # Intensity image of cell soma part soma_mean_bef = np.mean(self.RawRegionImg[np.where(self.cell_soma_mask_bef == 1)])#Mean pixel value of soma area contour_soma_ratio = contour_mean_bef/soma_mean_bef region_mean_intensity_list.append(filled_mean_bef)# Mean intensity of filled image region_circularit_list.append(regioncircularity) region_meanintensity_contour_list.append(contour_mean_bef) dirforcellprp[RegionLoopNumber] = (filled_mean_bef, contour_mean_bef, regioncircularity, contour_soma_ratio) RegionLoopNumber = RegionLoopNumber+1 #--------------------------------------------------Add red boundingbox to axis---------------------------------------------- rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2) contour_mean_bef_rounded = str(round(contour_mean_bef, 3))[0:5] if EachRound == 0: self.ax_showlabel.add_patch(rect) self.ax_showlabel.text((maxc + minc)/2, (maxr + minr)/2, 'Cell-{}, {}: {}'.format(RegionLoopNumber, 'c_m', contour_mean_bef_rounded),fontsize=8, color='yellow', style='italic')#,bbox={'facecolor':'red', 'alpha':0.3, 'pad':8}) # print('Total region number: {}'.format(RegionLoopNumber)) cell_properties = np.zeros(len(region_mean_intensity_list), dtype = dtype) for p in range(RegionLoopNumber): cell_properties[p] = dirforcellprp[p] CellPropDictEachRound['RoundSequence{}'.format(EachRound+1)] = cell_properties if EachRound == 0: self.ax_showlabel.set_axis_off() # if EachRound == 0: plt.show() return CellPropDictEachRound
def get_Skeletonized_contour(self, image, RegionProposalMask, smallest_size, contour_thres, contour_dilationparameter, cell_region_opening_factor, cell_region_closing_factor): cleared = RegionProposalMask.copy() clear_border(cleared) # label image regions, prepare for regionprops label_image = label(cleared) CellSkeletonizedContourDict = {} for region in regionprops(label_image,intensity_image = image): # USE first image in stack 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. # Based on the boundingbox for each cell from first image in the stack, raw image of slightly larger region is extracted from each round. self.RawRegionImg = image[max(minr-4,0):min(maxr+4, image[0].shape[0]), max(minc-4,0):min(maxc+4, image[0].shape[0])] # Raw region image self.RawRegionImg_for_contour = self.RawRegionImg.copy() #---------Get the cell filled mask------------- self.filled_mask_bef = imageanalysistoolbox.get_cell_filled_mask(RawRegionImg = self.RawRegionImg, region_area = region.area, cell_region_opening_factor = cell_region_opening_factor, cell_region_closing_factor = cell_region_closing_factor) # ============================================================================= # #---------------------------------------------------Get binary cell image baseed on expanded current region image------------------------------------------------- # # self.RawRegionImg = denoise_tv_chambolle(self.RawRegionImg, weight=0.01) # # # # thresh_regionbef = threshold_otsu(self.RawRegionImg) # # self.expanded_binary_region_bef = np.where(self.RawRegionImg >= thresh_regionbef, 1, 0) # # # # binarymask_bef = opening(self.expanded_binary_region_bef, square(int(cell_region_opening_factor))) # # self.expanded_binary_region_bef = closing(binarymask_bef, square(int(cell_region_closing_factor))) # # # # #---------------------------------------------------fill in the holes, prepare for contour recognition----------------------------------------------------------- # # seed_bef = np.copy(self.expanded_binary_region_bef) # # seed_bef[1:-1, 1:-1] = self.expanded_binary_region_bef.max() # # mask_bef = self.expanded_binary_region_bef # # # # self.filled_mask_bef = reconstruction(seed_bef, mask_bef, method='erosion')# The binary mask with filling holes # # # # #----------------------------------------------------Clean up parts that don't belong to cell of interest--------------------------------------- # # SubCellClearUpSize = int(region.area*0.35) # Assume that trash parts won't take up 35% of the whole cell boundbox area # # print(region.area) # # IndividualCellCleared = self.filled_mask_bef.copy() # # # # clear_border(IndividualCellCleared) # # # label image regions, prepare for regionprops # # IndividualCell_label_image = label(IndividualCellCleared) # # # # for subcellregion in regionprops(IndividualCell_label_image,intensity_image = self.RawRegionImg.copy()): # # # # if subcellregion.area < SubCellClearUpSize: # # # # for EachsubcellregionCoords in subcellregion.coords: # ## print(EachsubcellregionCoords.shape) # # self.filled_mask_bef[EachsubcellregionCoords[0], EachsubcellregionCoords[1]] = 0 # #------------------------------------------------------------------------------------------------------------------------------------------------ # ============================================================================= self.filled_mask_convolve2d = imageanalysistoolbox.smoothing_filled_mask(self.RawRegionImg, filled_mask_bef = self.filled_mask_bef, region_area = region.area) # ============================================================================= # # Shrink the image a bit. # self.filled_mask_bef = binary_erosion(self.filled_mask_bef, square(2)) # # Try to smooth the boundary. # kernel = np.ones((5,5)) # self.filled_mask_convolve2d = convolve2d(self.filled_mask_bef, kernel, mode='same') # try: # self.filled_mask_convolve2d = np.where(self.filled_mask_convolve2d >= threshold_otsu(self.filled_mask_convolve2d)*1.2, 1, 0) # Here higher the threshold a bit to shrink the mask, make sure generated contour doesn't exceed. # except: # pass # # Get rid of little patches. # # self.filled_mask_convolve2d = opening(self.filled_mask_convolve2d, square(int(1))) # #----------------------------------------------------Clean up parts that don't belong to cell of interest--------------------------------------- # SubCellClearUpSize = int(region.area*0.30) # Assume that trash parts won't take up 35% of the whole cell boundbox area # # print('minsize: '+str(SubCellClearUpSize)) # IndividualCellCleared = self.filled_mask_convolve2d.copy() # # clear_border(IndividualCellCleared) # # label image regions, prepare for regionprops # IndividualCell_label_image = label(IndividualCellCleared) # # for subcellregion_convolve2d in regionprops(IndividualCell_label_image,intensity_image = self.RawRegionImg.copy()): # # if subcellregion_convolve2d.area < SubCellClearUpSize: # # for EachsubcellregionCoords in subcellregion_convolve2d.coords: # # print(EachsubcellregionCoords.shape) # self.filled_mask_convolve2d[EachsubcellregionCoords[0], EachsubcellregionCoords[1]] = 0 # #------------------------------------------------------------------------------------------------------------------------------------------------ # ============================================================================= # Find contour along filled image imageanalysistoolbox_instacne=imageanalysistoolbox() contour_mask_bef = imageanalysistoolbox_instacne.contour(self.filled_mask_convolve2d, self.RawRegionImg_for_contour.copy(), contour_thres) # after here self.intensityimage_intensity is changed from contour labeled with number 5 to binary image contour_mask_of_cell = imageanalysistoolbox_instacne.inwarddilationmask(contour_mask_bef.copy() ,self.filled_mask_convolve2d, contour_dilationparameter) contour_origin_image_intensity = self.RawRegionImg*contour_mask_of_cell # Intensity image of cell contour # ============================================================================= # # Get the skeleton of the contour, same as contour_mask_bef # # contour_skeleton = skeletonize(contour_mask_of_cell)#, method='lee' # thinned_partial = thin(contour_mask_bef.copy(), max_iter=25) # ============================================================================= # -----------------------if cell appears on the border, complete the circle by connecting the two ends.---------------------------------- # print(len(np.where(thinned_partial[:, 0]==True)[0])) if len(np.where(thinned_partial[:, 0]==True)[0]) > 1:#return the column index of edge pixels. print('False on edge.') # thinned_partial[self.RawRegionImg.shape[0], :]==True # #---------------------------------------------------fill in the holes of the skeleton----------------------------------------------------------- # seed_bef_2 = np.copy(contour_skeleton) # seed_bef_2[1:-1, 1:-1] = contour_skeleton.max() # mask_bef_2 = contour_skeleton # # filled_mask_contour_skeleton = reconstruction(seed_bef_2, mask_bef_2, method='erosion')# The binary mask with filling holes # contour_skeleton_pruned = opening(contour_skeleton, square(int(cell_prune_opening_factor))) figure, (ax1, ax2) = plt.subplots(2, 1, figsize=(10,10)) ax1.imshow(self.RawRegionImg, cmap = plt.cm.gray) ax2.imshow(contour_mask_bef, cmap = plt.cm.gray) # ax2.imshow(contour_mask_of_cell, cmap = plt.cm.gray) # ax2.imshow(thinned_partial, cmap = plt.cm.gray) # figure.tight_layout() plt.show() #--------------------------------------------------Add red boundingbox to axis---------------------------------------------- # rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2) # # contour_mean_bef_rounded = str(round(contour_mean_bef, 3))[0:5] # self.ax_showlabel.add_patch(rect) # self.ax_showlabel.text((maxc + minc)/2, (maxr + minr)/2, 'Cell-{}, {}: {}'.format(RegionLoopNumber, 'c_m', contour_mean_bef_rounded),fontsize=8, color='yellow', style='italic')#,bbox={'facecolor':'red', 'alpha':0.3, 'pad':8}) return CellSkeletonizedContourDict
def get_intensity_properties(self, smallest_size, theMask, threshold, intensity_bef, intensty_aft, i, j, contour_thres, contour_dilationparameter, cell_region_opening, cell_region_closing): # remove artifacts connected to image border self.Labelmask = theMask # mask for general cell localization, so dosen't matter too much whose it is self.Imagbef = intensity_bef # Thresholded whole image 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 self.cell_openingfactor = cell_region_opening#1 self.cell_closingfactor = cell_region_closing#5 cleared = self.Labelmask.copy() clear_border(cleared) # label image regions label_image = label(cleared) dtype = [('Row index', 'i4'), ('Column index', 'i4'), ('Mean intensity', float), ('Mean intensity in contour', float), ('Circularity', float), ('Contour soma ratio', float), ('Change', float)] region_mean_intensity_list = [] region_circularit_list = [] region_meanintensity_contour_list = [] self.individual_cell_dic_bef = {} self.individual_cell_dic_aft = {} #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 loopmun = 0 dirforcellprp={} 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) regioncircularity = (4 * math.pi * region.filled_area) / (filledperimeter * filledperimeter) # region.perimeter will count in perimeters from the holes inside #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 = expanded_image_container_bef[minr:maxr+4, minc:maxc+4] # Raw region image self.regionimage_after = expanded_image_container_aft[minr:maxr+4, minc:maxc+4] 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 ''' plt.figure() plt.imshow(self.regionimage_before, cmap = plt.cm.gray) plt.show() ''' #print(np.max(self.regionimage_before)) # Get binary cell image baseed on expanded current region image thresh_regionbef = threshold_otsu(self.regionimage_before) self.expanded_binary_region_bef = np.where(self.regionimage_before >= thresh_regionbef, 1, 0) binarymask_bef = opening(self.expanded_binary_region_bef, square(self.cell_openingfactor)) self.expanded_binary_region_bef = closing(binarymask_bef, square(self.cell_closingfactor)) thresh_regionaft = threshold_otsu(self.regionimage_after) self.expanded_binary_region_aft = np.where(self.regionimage_after >= thresh_regionaft, 1, 0) binarymask_aft = opening(self.expanded_binary_region_aft, square(self.cell_openingfactor)) self.expanded_binary_region_aft = closing(binarymask_aft, square(self.cell_closingfactor)) ''' print('Original raw image:') plt.figure() plt.imshow(self.regionimage_before, cmap = plt.cm.gray) plt.show() ''' # fill in the holes seed_bef = np.copy(self.expanded_binary_region_bef) seed_bef[1:-1, 1:-1] = self.expanded_binary_region_bef.max() mask_bef = self.expanded_binary_region_bef self.filled_mask_bef = reconstruction(seed_bef, mask_bef, method='erosion')# The binary mask with filling holes seed_aft = np.copy(self.expanded_binary_region_aft) seed_aft[1:-1, 1:-1] = self.expanded_binary_region_aft.max() mask_aft = self.expanded_binary_region_aft self.filled_mask_aft = reconstruction(seed_aft, mask_aft, method='erosion')# fill in the holes filled_origin_image_intensity = self.regionimage_before*self.filled_mask_bef # Intensity image of cell with hole filled filled_mean_bef = np.mean(self.regionimage_before[np.where(self.filled_mask_bef == 1)]) # Mean pixel value of filled raw cell area # Find contour along filled image s=imageanalysistoolbox() contour_mask_bef = s.contour(self.filled_mask_bef, self.regionimage_before_for_contour.copy(), self.contour_thres) # after here self.intensityimage_intensity is changed from contour labeled with number 5 to binary image self.contour_mask_of_intensity_bef = s.inwarddilationmask(contour_mask_bef ,self.filled_mask_bef, self.contour_dilationparameter) contourimage_intensity_aft = s.contour(self.filled_mask_aft, self.regionimage_after_for_contour.copy(), self.contour_thres) # after here self.intensityimage_intensity is changed with contour labeled with number 5 self.contour_mask_of_intensity_aft = s.inwarddilationmask(contourimage_intensity_aft ,self.filled_mask_aft, self.contour_dilationparameter) contour_mean_bef = np.mean(self.regionimage_before[np.where(self.contour_mask_of_intensity_bef == 1)]) contour_mean_aft = np.mean(self.regionimage_after[np.where(self.contour_mask_of_intensity_aft == 1)]) self.cell_soma_mask_bef = self.filled_mask_bef - self.contour_mask_of_intensity_bef contour_origin_image_intensity = self.regionimage_before*self.contour_mask_of_intensity_bef # Intensity image of cell contour soma_origin_image_intensity = self.regionimage_before*self.cell_soma_mask_bef # Intensity image of cell soma part soma_mean_bef = np.mean(self.regionimage_before[np.where(self.cell_soma_mask_bef == 1)])#Mean pixel value of soma area contour_soma_ratio = contour_mean_bef/soma_mean_bef contour_change_ratio = contour_mean_aft/contour_mean_bef plt.figure() plt.imshow(self.contour_mask_of_intensity_bef, cmap = plt.cm.gray) plt.show() plt.figure() plt.imshow(self.contour_mask_of_intensity_aft, cmap = plt.cm.gray) plt.show() ''' ''' print('Contour soma ratio: '+str(round(contour_soma_ratio, 3))) print('Contour image:') plt.figure() plt.imshow(contour_origin_image_intensity, cmap = plt.cm.gray) plt.show() print('Soma image:') plt.figure() plt.imshow(soma_origin_image_intensity, cmap = plt.cm.gray) plt.show() #print(region_mean_intensity) region_mean_intensity_list.append(filled_mean_bef)# Mean intensity of filled image region_circularit_list.append(regioncircularity) region_meanintensity_contour_list.append(contour_mean_bef) dirforcellprp[loopmun] = (self.row_num, self.column_num, filled_mean_bef, contour_mean_bef, regioncircularity, contour_soma_ratio, contour_change_ratio) loopmun = loopmun+1 print('Total region number: {}'.format(loopmun)) cell_properties = np.zeros(len(region_mean_intensity_list), dtype = dtype) for p in range(loopmun): cell_properties[p] = dirforcellprp[p] return cell_properties, self.expanded_binary_region_bef, contour_origin_image_intensity, self.intensityimage_intensity, contour_change_ratio
def get_intensity_properties(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.row_num = i self.column_num = j self.threshold = threshold self.Imageaft = intensty_aft self.contour_thres = contour_thres self.contour_dilationparameter = contour_dilationparameter 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), ('Mean intensity in contour', float), ('Circularity', float), ('Change', float)] region_mean_intensity_list = [] region_circularit_list = [] region_meanintensity_contour_list = [] loopmun = 0 dirforcellprp = {} 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] #print(self.Imagbef[region.coords[0][0]][region.coords[0][1]]) #localthresh = threshold_otsu(self.regionimage_after)-0.1 #print(localthresh) #singlethresh = True #print(region.area) #print(region.bbox_area) #print(region_mean_intensity) s = imageanalysistoolbox() contourimage_intensity = s.contour( filledimg, self.intensityimage_intensity, self.contour_thres ) # after here self.intensityimage_intensity is changed with contour labeled with number 5 contour_mask_of_intensity = s.inwarddilationmask( contourimage_intensity, filledimg, self.contour_dilationparameter) #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 contour_origin_image_intensity = contour_mask_of_intensity * self.regionimage_before # Calculate mean contour intensity of image before perfusion contourprops_bef = regionprops(contour_mask_of_intensity, self.regionimage_before) contour_mean_bef = contourprops_bef[0].mean_intensity # Calculate mean contour intensity of image after perfusion contourprops_aft = regionprops(contour_mask_of_intensity, self.regionimage_after) contour_mean_aft = contourprops_aft[0].mean_intensity #print('contour_mean_bef:'+str(contour_mean_bef)) #Calculate the intensity change ratio = contour_mean_aft / contour_mean_bef #print(region_mean_intensity) region_mean_intensity_list.append(region_mean_intensity) region_circularit_list.append(regioncircularity) region_meanintensity_contour_list.append(contour_mean_bef) dirforcellprp[loopmun] = (self.row_num, self.column_num, region_mean_intensity, contour_mean_bef, regioncircularity, ratio) 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, contour_mask_of_intensity, contour_origin_image_intensity, self.regionimage_before, ratio