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 round_regions(image, initial_radius=25, delta_radius=2, toler_ecc=0.5): ''' ''' info_regions = [] img_objects = np.zeros(image.shape) thresh = threshold_isodata(image) img_bin = binary_fill_holes(image < thresh) img_bin = morphology.remove_small_objects(img_bin) img_labels, _, _ = segmentation_wusem(img_bin, initial_radius=initial_radius, delta_radius=delta_radius) properties = regionprops(img_labels, intensity_image=image) for prop in properties: if prop.eccentricity > toler_ecc: img_labels[img_labels == prop.label] = 0 else: info_regions.append([ prop.label, prop.minor_axis_length, prop.major_axis_length, prop.mean_intensity ]) rows, cols = np.where(img_labels != 0) img_objects[rows, cols] = image[rows, cols] return img_labels, img_objects, info_regions
def auto_threshold(image, filter_type, return_filt=False): blurred = cv2.GaussianBlur(image, (3, 3), 0) if filter_type == 'otsu': filt = f.threshold_otsu(blurred) bw = blurred > filt bw = bw.astype(int) elif filter_type == 'isodata': filt = f.threshold_isodata(blurred) bw = blurred > filt bw = bw.astype(int) elif filter_type == 'triangle': filt = f.threshold_triangle(blurred) bw = blurred > filt bw = bw.astype(int) elif filter_type == 'entropy': filt = f.threshold_li(blurred) bw = blurred > filt bw = bw.astype(int) elif filter_type == 'mixed': snr = np.mean(blurred) / np.std(blurred) if snr > 2: filt = f.threshold_triangle(blurred) else: filt = f.threshold_otsu(blurred) bw = image > filt bw = bw.astype(int) if return_filt: return bw, filt else: return bw
def gray_to_binary_with_thresh_method(image, is_gray, thresh_method): ### Set image to graycale if needed if is_gray == 0: ### Convert to grayscale grayscale = rgb2gray(image) elif is_gray == 1: ### Does nothing to the image, already grayscale grayscale = image ### Determine threshold method to use according to parameter thresh_method if thresh_method == 'yen': ### Calculate treshold according to yen method thresh = threshold_yen(grayscale) elif thresh_method == 'isodata': ### Calculate treshold according to isodata method thresh = threshold_isodata(grayscale) else: print('Invalid threshold method! Please choose isodata or yen. ') ### Generate binary image binary = grayscale > thresh ### Show thresholded image plt.imshow(binary, cmap='gray') plt.show() cv2.waitKey(0) cv2.destroyAllWindows() ### Return binary image return binary
def traditional_seg(im): tsh = threshold_isodata(im, return_all=False) bw = im > tsh bw = binary_closing(bw, selem=disk(3)) bw = binary_opening(bw, selem=disk(3)) bw = remove_small_objects(bw, min_size=1024) return bw.astype(int)
def show_thresholds(): images = f['images'] filenames = f['filenames'] for i in range(21, 40): image = images[i] thresholds = { "thresh_yen": skfilt.threshold_yen(image), "thresh_otsu": skfilt.threshold_otsu(image), "thresh_li": skfilt.threshold_li(image), "thresh_iso": skfilt.threshold_isodata(image) } name = filenames[i] fig = plt.figure(i) arr = np.asarray(image) ax = fig.add_subplot(3, 2, 1) ax.imshow(arr, cmap='gray') ax.set_title(name) for i_plt, thresh_type in enumerate(thresholds.keys()): thresh_val = thresholds[thresh_type] ax1 = fig.add_subplot(3, 2, i_plt + 2) ax1.imshow(image > thresh_val, interpolation='nearest', cmap='gray') ax1.set_title(thresh_type + ": {}".format(np.round(thresholds[thresh_type]))) plt.show()
def compute_base_mask(self, params): """Creates the base mask for the base image. Needs the base image, an instance of imageloaderparams and the clip area, which should be already defined by the load_base_image method To create the base mask, two algorithms are available, on based on the threshold_isodata and the other one on the threshold_adaptive functions of the scikit-image.threshold module. """ x0, y0, x1, y1 = self.clip base_mask = np.copy(self.base_image[x0:x1, y0:y1]) if params.mask_algorithm == "Isodata": isodata_threshold = threshold_isodata(base_mask) base_mask = img_as_float(base_mask <= isodata_threshold) elif params.mask_algorithm == "Local Average": # need to invert because threshold_adaptive sets dark parts to 0 base_mask = 1.0 - threshold_adaptive(base_mask, params.mask_blocksize, offset=params.mask_offset) else: print "Not a valid mask algorithm" self.base_mask = 1 - base_mask
def threshold(image, mode='sk'): if (mode == 'sk'): th = filters.threshold_isodata(image) elif (mode == 'cv'): ret, th = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return (image < th)
def compute_base_mask(self, params): """Creates the base mask for the base image. Needs the base image, an instance of imageloaderparams and the clip area, which should be already defined by the load_base_image method To create the base mask, two algorithms are available, on based on the threshold_isodata and the other one on the threshold_adaptive functions of the scikit-image.threshold module. """ x0, y0, x1, y1 = self.clip base_mask = np.copy(self.base_image[x0:x1, y0:y1]) if params.mask_algorithm == "Isodata": isodata_threshold = threshold_isodata(base_mask) base_mask = img_as_float(base_mask <= isodata_threshold) elif params.mask_algorithm == "Local Average": # need to invert because threshold_adaptive sets dark parts to 0 block_size = params.mask_blocksize if block_size % 2 == 0: block_size += 1 base_mask = 1.0 - threshold_adaptive( base_mask, block_size, offset=params.mask_offset) else: print "Not a valid mask algorithm" self.base_mask = 1 - base_mask
def trim(image): '''transforms the given image to crop and orient the strips''' scale_factor = 5 temp = rgb2gray(image) temp = downscale_local_mean(temp, (scale_factor, scale_factor)) e = rank.entropy(temp, disk(10)) fred = binary_fill_holes(e > threshold_isodata(e)) fred = rank.minimum(fred, disk(10)) labels = label(fred) props = regionprops(labels) areas = [prop['area'] for prop in props] selection = labels == props[np.argmax(areas)]['label'] angles = np.linspace(-45, 45) rotations = [rotate(selection, angle, resize=True) for angle in angles] props = [regionprops(label(r)) for r in rotations] bboxes = [prop[0]['bbox'] for prop in props] areas = [(bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) for bbox in bboxes] best = np.argmin(areas) rotated = rotations[best] mask = rank.minimum(rotated, square(10)) > 0 bbox = np.array(regionprops(label(mask))[0]['bbox']) rmin, cmin, rmax, cmax = bbox * scale_factor transformed = rotate(image, angles[best], resize=True) transformed = transformed[rmin:rmax, cmin:cmax] return transformed
def binarize_imageset(image_set): imgbin_otsu, imgbin_yen, imgbin_li, imgbin_iso, imgbin_tri, imgbin_mlss = [ [] for _ in range(6) ] for idx, img in enumerate(image_set): # Filtering #img = ndimage.median_filter(img, size=(7, 7)) img = denoise_tv_chambolle(img, weight=0.05) #img = rescale_intensity(img, in_range=(0, 0.5)) # Otsu imgbin_otsu.append(binarize_imageset_aux(img < threshold_otsu(img))) # Yen imgbin_yen.append(binarize_imageset_aux(img < threshold_yen(img))) # Li imgbin_li.append(binarize_imageset_aux(img < threshold_li(img))) # ISODATA imgbin_iso.append(binarize_imageset_aux(img < threshold_isodata(img))) # MLSS aux = pd.read_csv('auto_count/mlss/imgbin_mlss' + str(idx + 1) + '.csv') imgbin_mlss.append(binarize_imageset_aux(np.asarray(aux, dtype='bool'))) return imgbin_otsu, imgbin_yen, imgbin_li, imgbin_iso, imgbin_mlss
def apply(self, matrix): binary = [] if self.func == 'global': value = 0 if self.method == 'otsu': value = threshold_otsu(matrix) if self.method == 'isodata': value = threshold_isodata(matrix) if self.method == 'yen': value = threshold_yen(matrix) if self.method == 'median': value = numpy.median(matrix) if self.method == 'kmeans': aa = numpy.array(matrix).reshape(-1) aa.shape = (aa.shape[0], 1) cc = k_means(aa, 5) ccc = cc[0].reshape(-1) ccc.sort() value = ccc[len(ccc) - 2] binary = matrix > value if self.func == 'adaptive': binary = threshold_adaptive(matrix, 127, self.method) return binary.astype('float')
def compute_sept_isodata(self, mask, thick, septum_base): """Method used to create the cell sept_mask using the threshold_isodata to separate the cytoplasm from the septum""" cell_mask = mask if septum_base: fluor_box = 1 - self.base_box else: fluor_box = self.fluor perim_mask = self.compute_perim_mask(cell_mask, thick) inner_mask = cell_mask - perim_mask inner_fluor = (inner_mask > 0) * fluor_box threshold = threshold_isodata(inner_fluor[inner_fluor > 0]) interest_matrix = inner_mask * (inner_fluor > threshold) label_matrix = label(interest_matrix, connectivity=2) interest_label = 0 interest_label_sum = 0 for l in range(np.max(label_matrix)): if np.sum(img_as_float(label_matrix == l + 1)) > interest_label_sum: interest_label = l + 1 interest_label_sum = np.sum(img_as_float(label_matrix == l + 1)) return img_as_float(label_matrix == interest_label)
def auto_threshold(image,filter_type): if filter_type=='otsu': filt= f.threshold_otsu(image) bw= image>filt bw=bw.astype(int) elif filter_type=='isodata': filt= f.threshold_isodata(image) bw= image>filt bw=bw.astype(int) elif filter_type=='triangle': filt= f.threshold_triangle(image) bw= image>filt bw=bw.astype(int) elif filter_type=='entropy': filt= f.threshold_li(image) bw= image>filt bw=bw.astype(int) elif filter_type=='mixed': snr=np.mean(image)/np.std(image) if snr>2: filt= f.threshold_triangle(image) else: filt= f.threshold_otsu(image) bw= image>filt bw=bw.astype(int) return bw
def init_Segmentation(phase_contrast_img, shape_indexing_sigma=2): # shape_indexed = Shape_indexing_normalization(phase_contrast_img, \ shape_indexing_sigma=shape_indexing_sigma) # ph_gau = filters.gaussian(phase_contrast_img, sigma=1) ph_binary_glob = (ph_gau < filters.threshold_isodata(ph_gau)) * 1 ph_binary_local = (ph_gau < filters.threshold_local( ph_gau, method="mean", block_size=15)) ph_binary_local[morphology.dilation(ph_binary_glob, morphology.disk(5)) == 0] = 0 ph_binary_local.dtype = bool ph_binary_local = morphology.remove_small_objects(ph_binary_local, min_size=80) ph_binary_local = morphology.remove_small_holes(ph_binary_local, area_threshold=80) * 1 ph_binary_local = morphology.opening(ph_binary_local, morphology.disk(1)) * 1 # deprecated #if use_shape_indexed_binary: # shape_indexed_binary = util.invert(shape_indexed > filters.threshold_local(shape_indexed, 27)) # shape_indexed_binary[ph_binary_local == 0] = 0 # shape_indexed_binary = (filters.median(shape_indexed_binary, morphology.disk(3)))*1 # shape_indexed_binary = (morphology.remove_small_holes(shape_indexed_binary, area_threshold=100))*1 # microcolony_labels = measure.label(ph_binary_local, connectivity=1) region_info = measure.regionprops(microcolony_labels, coordinates='xy') #return ph_binary_local, shape_indexed, shape_indexed_binary, microcolony_labels, region_info return ph_binary_local, shape_indexed, microcolony_labels, region_info
def locateONH(enface): #average across x and y to get the mean a-scan profile profile = np.mean(enface, axis=(1, 2)) #find the max and get the index max_frame_ind = np.squeeze(np.array(np.where(profile == np.max(profile)))) #get the max frame max_frame = enface[max_frame_ind] #gaussian blur gmax = sf.gaussian(max_frame, sigma=2) #automatic thresholding using the isodata algorithm isodata_thresh = sf.threshold_isodata(gmax) #invert the binary image to the onh can be segmented classified_img = gmax < isodata_thresh #find connected regions using 8-connectivity (a square) labels = sm.label(classified_img, connectivity=2) #find the properties of those regions props = sm.regionprops(labels) #detect which is the onh onh_ind = max_area(props) #save csv with centroid props[onh_ind].centroid #return bounding box indicies to use for b-scan cleaning function if onh_ind != -1: ymin = props[onh_ind].bbox[0] ymax = props[onh_ind].bbox[2] return [ymin, ymax] elif onh_ind == -1: #this means no onh spot was detected #preferable to fix, if possible. return [-1, -1]
def compare(true_img, pred_img, out=False): true_img = true_img > threshold_isodata(true_img) pred_img = pred_img > threshold_isodata(pred_img) TP = np.sum(np.logical_and(true_img == 1, pred_img == 1)) TN = np.sum(np.logical_and(true_img == 0, pred_img == 0)) FP = np.sum(np.logical_and(true_img == 0, pred_img == 1)) FN = np.sum(np.logical_and(true_img == 1, pred_img == 0)) precision = TP / (TP + FP) recall = TP / (TP + FN) accu = (TP + TN) / (TP + TN + FP + FN) if out: return [precision, recall, accu] else: return [TP, TN, FP, FN]
def extractionCloud(input): """ 1. 将图片进行判断是否含有其他的物体 2. 使用阈值将图片进行除云以外的物体过滤,获得二值图像 :return: """ # 将数据加载类中的Tensor转换成numpy中的array并转化成(width,hight,channel_number) input = input.numpy( ) # 形状为(mini-batch-number, channel_number, width,hight) input_squeeze = np.squeeze(input) # 降维(channel_number, hight, width) input_squeeze = input_squeeze.reshape(input_squeeze.shape[0], input_squeeze.shape[1], 3) # 判断是否有其他的目标 if pictureSimilarity(input_squeeze, 0.7) is False: thresh = filters.threshold_isodata(input_squeeze) # 返回一个阈值 input_dst = (input_squeeze <= thresh) * 1.0 # 根据阈值进行分割,得到一个二值图像 else: input_dst = (input_squeeze <= 0) * 1.0 # plt.figure('thresh', figsize=(8, 8)) # plt.axis('off') # plt.subplot(121) # #plt.title('original image', plt.cm.gray) # plt.imshow(input_squeeze) # # plt.subplot(122) # #plt.title('binary image', plt.cm.gray) # plt.imshow(input_dst, plt.cm.get_cmap()) # # plt.show() return input_squeeze, input_dst
def compute_sept_isodata(self, mask, thick, septum_base): """Method used to create the cell sept_mask using the threshold_isodata to separate the cytoplasm from the septum""" cell_mask = mask if septum_base: fluor_box = 1 - self.base_box else: fluor_box = self.fluor perim_mask = self.compute_perim_mask(cell_mask, thick) inner_mask = cell_mask - perim_mask inner_fluor = (inner_mask > 0) * fluor_box threshold = threshold_isodata(inner_fluor[inner_fluor > 0]) interest_matrix = inner_mask * (inner_fluor > threshold) label_matrix = label(interest_matrix, connectivity=2) interest_label = 0 interest_label_sum = 0 for l in range(np.max(label_matrix)): if np.sum( img_as_float(label_matrix == l + 1)) > interest_label_sum: interest_label = l + 1 interest_label_sum = np.sum(img_as_float(label_matrix == l + 1)) return img_as_float(label_matrix == interest_label)
def cont(imagen, depth=2**16, gaussian=3, screenpercent=0.7,t=0): imagen = gaussian_filter(imagen, gaussian) if t==0: otsu = threshold_otsu(imagen, depth) elif t==1: otsu = filters.threshold_isodata(imagen, depth) else: otsu = filters.threshold_li(imagen) imagen = binarizar(imagen, otsu) imagen = gaussian_filter(imagen, gaussian) contours = measure.find_contours(imagen, 1) centro = np.asanyarray([1280*0.5, 960*0.5]) while len(contours) > 1: if sum(np.abs(centro - contours[1].mean(axis=0)) < [1280*screenpercent*0.5, 960*screenpercent*0.5]) != 2: del contours[1] elif sum(np.abs(centro - contours[0].mean(axis=0)) < [1280*screenpercent*0.5, 960*screenpercent*0.5]) != 2: del contours[0] else: if contours[1].size < contours[0].size: del contours[1] else: del contours[0] return imagen, contours[0]
def __init__(self, directory, glob_pattern, fluor_channel_list, bin_trans=True, min_dist_pixels=10): from glob import glob import os from skimage.io import imread from skimage.filters import threshold_isodata from skimage.feature import peak_local_max from skimage.measure import label from skimage.transform import downscale_local_mean from skimage.segmentation import watershed from scipy.ndimage.morphology import distance_transform_edt import sys # add local directories to sys.path sys.path.append('unet') import unet.neural_network as nn from unet.segment import cell_merge, correct_artefacts # assign attributes self.directory = directory self.glob_pattern = glob_pattern self.fluor_channel_list = fluor_channel_list self.bin_trans = True self.min_dist_pixels = min_dist_pixels # generate masks glob_files = glob(os.path.join(directory, glob_pattern)) self.glob_files = glob_files # the glob pattern should contain all trans image files to process mask_im_list = [] fluor_list_list = [] #this will be a list of lists trans_im_list = [] for i, file in enumerate(glob_files): print('Processing image ' + str(i+1) + ' of ' +str(len(glob_files))) im_trans = imread(file) trans_im_list.append(im_trans) if bin_trans: im_trans = downscale_local_mean(im_trans, (2,2)) im_prediction = nn.prediction(im_trans, True) threshold_value = threshold_isodata(im_prediction) im_binary = im_prediction im_binary[im_binary > threshold_value] = 255 im_binary[im_binary <= threshold_value] = 0 im_distance_transform = distance_transform_edt(im_binary) im_peaks = peak_local_max(im_distance_transform, min_distance=min_dist_pixels, indices=False) im_label = label(im_peaks) im_watershed = watershed(-im_distance_transform, markers=im_label, mask=im_binary, connectivity=2) im_merged = cell_merge(im_watershed, im_prediction) im_correct = correct_artefacts(im_merged) mask_im_list.append(im_correct) # read in the fluor channels channel_im_list = [] for channel_string in fluor_channel_list: channel_im = imread(file.replace('Trans', channel_string)) channel_im_list.append(channel_im) fluor_list_list.append(channel_im_list) self.mask_im_list = mask_im_list self.fluor_list_list = fluor_list_list self.trans_im_list = trans_im_list
def test_routine(self): markers = ['avanti', 'Rutenium Red'] si = SequenceImporter(markers) img, channel_names = si(self.settings.input_folder) image = np.mean(img, axis=2) image_downscale = rescale(image, .25) perc = np.percentile(image_downscale, [80, 99]) low_val = perc[0] high_val = perc[1] image = 255 * (image_downscale - low_val) / (high_val - low_val) image[image>255] = 255 image[image<0] = 0 image = image.astype(np.uint8) pref1 = median(image, disk(3)) pref2 = gaussian(pref1, .5) thresh = threshold_isodata(pref2) binary = pref2 > thresh binary_closed = closing(binary, square(8)) clean_binary = remove_small_objects(binary_closed, 30) temp = dilation(clean_binary, disk(2)) output = closing(temp, square(15)) if self.settings.debug: out_folder = os.path.join(self.settings.debug_folder, 'fissure') if not os.path.isdir(out_folder): os.makedirs(out_folder) filename = os.path.join(out_folder, 'debug_fissure_median.png') skimage.io.imsave(filename, pref1) filename = os.path.join(out_folder, 'debug_fissure_gauss.png') skimage.io.imsave(filename, pref2) filename = os.path.join(out_folder, 'debug_fissure_binary_closed.png') skimage.io.imsave(filename, 255 * binary_closed) filename = os.path.join(out_folder, 'debug_fissure_normalized.png') skimage.io.imsave(filename, image) filename = os.path.join(out_folder, 'debug_thresh_isodata.png') skimage.io.imsave(filename, 255 * binary) filename = os.path.join(out_folder, 'debug_thresh_clean.png') skimage.io.imsave(filename, 255 * clean_binary) filename = os.path.join(out_folder, 'debug_thresh_dilated.png') skimage.io.imsave(filename, 255 * temp) filename = os.path.join(out_folder, 'debug_thresh_output.png') skimage.io.imsave(filename, 255 * output) return output
def threshold(self, thresh, **kwargs): """Threshold the image Parameters ---------- thresh : str or float If a float in [0,1] is provided, pixels whose grayscale value is above said threshold will be white, others black. A number of additional methods are supported: * 'mean': Threshold image based on the mean of grayscale values. * 'minimum': Threshold image based on the minimum method, where the histogram of the input image is computed and smoothed until there are only two maxima. * 'local': Threshold image based on `local pixel neighborhood <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_local>_. Requires ``block_size``: odd number of pixels in the neighborhood. * 'otsu': `Otsu's method <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_otsu>_ * 'isodata': `ISODATA method <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_isodata>`_, also known as the Ridler-Calvard method or intermeans. Returns ------- stim : `ImageStimulus` A copy of the stimulus object with two gray levels 0.0 and 1.0 """ if len(self.img_shape) > 2: raise ValueError("Thresholding is only supported for grayscale " "(i.e., single-channel) images. Use `rgb2gray` " "first.") img = self.data.reshape(self.img_shape) if isinstance(thresh, str): if thresh.lower() == 'mean': img = img > threshold_mean(img) elif thresh.lower() == 'minimum': img = img > threshold_minimum(img, **kwargs) elif thresh.lower() == 'local': img = img > threshold_local(img, **kwargs) elif thresh.lower() == 'otsu': img = img > threshold_otsu(img, **kwargs) elif thresh.lower() == 'isodata': img = img > threshold_isodata(img, **kwargs) else: raise ValueError("Unknown threshold method '%s'." % thresh) elif np.isscalar(thresh): img = self.data.reshape(self.img_shape) > thresh else: raise TypeError("Threshold type must be str or float, not " "%s." % type(thresh)) return ImageStimulus(img, electrodes=self.electrodes, metadata=self.metadata)
def threshold_isodata(source): try: thresholds = skif.threshold_isodata(source, return_all=True); if len(thresholds) > 0: return thresholds[-1]; else: return 1; except: return 1;
def make_binary_image(im, white_background, min_feature_size, small): image = im.astype('float32') if white_background: image = np.abs(image - np.max(image)) # get rid of large background patches before local thresholding # do a global threshold thresh = threshold_isodata(image) binary = image > thresh # get rid of speckle # this is not good for very small particles if not small: binary_closing(binary, selem=disk(min_feature_size), out=binary) # make a map of the distance to a particle to find large background patches # this is a distance map of the inverse binary image distance = ndimage.distance_transform_edt(1 - binary) # dilate the distance map to expand small voids #distance = ndimage.grey_dilation(distance,size=2*min_feature_size) # do a global threshold on the distance map to select the biggest objects # larger than a minimum size to prevent masking of particles in images with no empty patches dist_thresh = threshold_isodata(distance) mask = distance < dist_thresh # remove areas of background smaller than a certain size in the mask # this fills in small pieces of mask between particles where the voronoi # vertices will end up # this gets rid of junk in the gap areas binary_opening(mask, selem=disk(min_feature_size), out=mask) binary = binary * mask # get rid of speckle binary = remove_small_objects(binary, min_size=max(min_feature_size, 2)) # 3 iterations is better for large particles with low contrast binary = ndimage.binary_closing(binary, iterations=3) return binary, mask
class BinaryAlg: _operations = { 'Isodata': lambda x : 1*((abs(x) > skfilters.threshold_isodata(x))), 'Li': lambda x : 1*((abs(x) > skfilters.threshold_li(x))), 'Mean': lambda x : 1*((abs(x) > skfilters.threshold_mean(x))), 'Minimum': lambda x : 1*((abs(x) > skfilters.threshold_minimum(x))), 'Otsu': lambda x : 1*((abs(x) > skfilters.threshold_otsu(x))), 'Triangle': lambda x : 1*((abs(x) > skfilters.threshold_triangle(x))), 'Yen': lambda x : 1*((abs(x) > skfilters.threshold_yen(x))) }
def hysteresis(image, alpha=1.0): """Hystersis thresholding with low and high clipped values determined by the mean, li and isodata threshold""" low = np.min([alpha * threshold_mean(image), threshold_li(image)]) high = threshold_isodata(image) threshold = apply_hysteresis_threshold(image, low, high) return threshold
def adaptive_binary_image(im, white_background, min_feature_size, std_dev, mask): image = im.astype('float32') if white_background: image = np.abs(image - np.max(image)) # the block size should be large enough to include 4 to 9 particles local_size = 40 * min_feature_size binary = image > threshold_local(image, block_size=local_size + 1) # plt.imshow(binary) # plt.show() # close any small holes in the particles # 3 iterations is better for large particles with low contrast binary = ndimage.binary_closing(binary, iterations=1) # binary_closing(binary, selem=disk(int(max((0.414*(min_feature_size-std_dev)),2)/2.0)), out=binary) # plt.imshow(binary) # plt.show() # remove speckle from background areas in the binary image binary = binary * mask #binary_erosion(mask, selem=disk(int(min_feature_size))) binary_opening(binary, selem=disk( int(max((min_feature_size - 3.0 * std_dev), 2) / 2.0)), out=binary) # make a distance map of the inverted image distance = ndimage.distance_transform_edt((1 - binary)) # do a global threshold on the distance map to select the biggest objects # larger than a minimum size to prevent masking of particles in images with no empty patches dist_thresh = threshold_isodata(distance) new_mask = distance < dist_thresh # thresholding is selecting too much background, try AND'ing it with the binary image # this might only be necessary for small particles new_mask = new_mask * binary # remove areas of background in the mask smaller than a certain size # this fills in small pieces of mask between particles where the voronoi # vertices will end up # min_feature_size here should be the radius found by global threshold, so triple it # to close any particle sized holes dilation_size = max(int(1), int(3 * min_feature_size)) new_mask = binary_closing(new_mask, selem=np.ones((dilation_size, dilation_size))) plt.imshow(new_mask) plt.show() return binary, new_mask
def binarization(data, banda, bins): w = data.getSceneRasterWidth() h = data.getSceneRasterHeight() band = data.getBand(banda) band_data = np.zeros(w * h, np.float32) hist = plt.hist(np.asarray(band_data, dtype='float'), bins=bins, range=[-33, -1]) return threshold_isodata(np.asarray(band_data, dtype='float'), return_all=True)
def preprocessing_dt(img, feature_size=7000, feature_number=1, despeckle_size=10): mask = get_chain_mask(img, feature_size, feature_number) isod = img > filters.threshold_isodata(img) masked_isod = mask * isod despeck = ndimage.median_filter(masked_isod, size=despeckle_size) dt = ndimage.distance_transform_edt(despeck) filt = matlab_style_gauss2D(shape=(3, 3)) conv = signal.convolve2d(dt, filt, mode='same') return conv
def seuillage(img): # seuil= int(input('Veuillez saisir la valeur du SEUIL:')) seuil = 20 imgS = filters.threshold_isodata(img) <= img fig = plt.figure() fig.add_subplot(1, 2, 1) plt.imshow(img, cmap='gray') fig.add_subplot(1, 2, 2) plt.imshow(imgS, cmap='gray') plt.show() return imgS
def skimage_threshold(img, method='isodata'): if not img.dtype == np.uint8: print('skimage_threshold NORM because received: ', img.dtype) img = normalize(img) thresh = { 'otsu': filters.threshold_otsu(img), # delivers very high threshold 'yen': filters.threshold_yen(img), # delivers even higher threshold 'isodata': filters.threshold_isodata(img), # works extremely well }.get(method, 0) # None is default value if thresh == 0: print(' *** ERROR - skimage_threshold select THRESHOLD = 0 ***') return thresh, cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY)[1]
def getThresholded(self, img, abs=True): if abs: im = self.runHistogramAbs(img) else: im = self.runHistogram(img) try: threshold = threshold_isodata(im) except: return img im = im > threshold filled = binary_fill_holes(im).astype(int) mask = binary_closing(filled) return mask
def make_segment(case_nr, params): img = plt.imread(R"result\r{}.png".format(case_nr)) img_hsv = clr.rgb2hsv(img) img_value = img_hsv[:, :, 2] v_std = np.std(img_value) img_value = (img_value - params[0]) * (params[1] / v_std) manipulation = np.abs(img_value) if params[2] == 0: thresh = flt.threshold_otsu(manipulation) binary = manipulation > thresh elif params[2] == 1: thresh = flt.threshold_isodata(manipulation) binary = manipulation > thresh elif params[2] == 2: thresh = flt.threshold_li(manipulation) binary = manipulation > thresh elif params[2] == 3: thresh = flt.threshold_mean(manipulation) binary = manipulation > thresh elif params[2] == 4: thresh = flt.threshold_niblack(manipulation) binary = manipulation > thresh elif params[2] == 5: thresh = flt.threshold_sauvola(manipulation) binary = manipulation > thresh elif params[2] == 6: thresh = flt.threshold_triangle(manipulation) binary = manipulation > thresh else: thresh = flt.threshold_yen(manipulation) binary = manipulation > thresh binary = morph.remove_small_holes(binary, area_threshold=100) binary = morph.remove_small_objects(binary, min_size=70, connectivity=2) return binary
def segmentation(image, method='otsu'): if (method == 'region'): sobel_image = filters.sobel(image) makers = sobel_image < sobel_image.max()*0.1 makers = ndi.label(makers)[0] labels = watershed(sobel_image,makers) elif (method == 'edge'): edges = canny(image,3) fill = ndi.binary_fill_holes(edges) labels = remove_small_objects(fill,10) elif (method == 'self_design'): width = 100; scale = 0.72; [m, n] = image.shape thre = np.zeros((m,n)) for i in range(0,n): ind_s = max(0,int(np.ceil(i-width/2))) ind_e = min(n-1,ind_s+width) current_image = image[0:m-1, ind_s:ind_e] thre[0:m-1, i] = filters.threshold_otsu(current_image)*0.8 labels = (image - thre) >=0 elif (method == 'thre_cons'): global_thre = image.max() * 0.3 labels = image > global_thre elif (method == 'global_otsu'): global_thre = filters.threshold_otsu(image) labels = image > global_thre elif (method == 'local_otsu'): selem=disk(80) local_otsu = filters.rank.otsu(image, selem) labels = image > (np.true_divide(local_otsu,255)) elif (method == 'yen'): global_thre = filters.threshold_yen(image) labels = image > (global_thre*2.5) elif (method == 'li'): global_thre = filters.threshold_li(image) labels = image > global_thre elif (method == 'isodata'): global_thre = filters.threshold_isodata(image) labels = image > global_thre elif (method == 'adaptive'): block_size = 100 image = np.true_divide(image,image.max()+np.spacing(1)) * 255 labels = filters.threshold_adaptive(image, block_size, offset=10) elif (method == 'R_Walker'): data = image + 0.35 * np.random.randn(*image.shape) markers = np.zeros(data.shape, dtype=np.uint) markers[data < -0.3] = 1 markers[data > 1.3] = 2 labels = random_walker(data, markers, beta=10, mode='cg_mg') return labels
def iso_func(img_slice): return filters.threshold_isodata(img_slice)
return(iPan) gitHome = os.getenv('GIT_HOME') imRel = '/OSImageAnalysis/images/blobs.gif' fi = gitHome + imRel print(fi) im =io.imread(fi) print(im.shape, im.dtype) binThrAd = filters.threshold_adaptive(im,21, method='median', offset=0, mode='reflect', param=None) thrIso = filters.threshold_isodata(im, nbins=256, return_all=False) binIso = im > thrIso tiIso = "Iso %d" % thrIso print(thrIso) thrLi = filters.threshold_li(im) binLi = im > thrLi tiLi = "Li %d" % thrLi thrOtsu = filters.threshold_otsu(im, nbins=256) binOtsu = im > thrOtsu tiOtsu = "Otsu %d" % thrOtsu thrYen = filters.threshold_yen(im, nbins=256) binYen = im > thrYen tiYen = "Yen %d" % thrYen
#plt.imshow(binary, cmap=plt.cm.gray) #plt.show() #image = data.imread("/Users/exequiel/projects/roots/python/processing/1.15.AVI/selected/frame-54.tiff") block_size = 35 gray = rgb2gray(image) global_thresh = threshold_otsu(gray) print global_thresh global_thresh = 0.65 for t in np.linspace(global_thresh,1.0,20): binary_global = gray > t #binary_global = gray > 0.90 print "threshold_otsu",threshold_otsu(gray) print "threshold_isodata",threshold_isodata(gray) print "threshold_li",threshold_li(gray) print "threshold_yen",threshold_yen(gray) label_img = label(binary_global, connectivity=binary_global.ndim) props = regionprops(label_img) boxes = [] for pp in props: minr, minc, maxr, maxc = pp.bbox boxes += [(minc, minr, maxc - minc, maxr - minr)] valid_boxes = filter_valid_boxes(boxes,6,40,14,24,300,900)
def save_data(params): name = params.name gesture = params.gesture display = params.display controller = display.controller devices = controller.devices if len(devices) == 0: return 'no_device' frame = controller.frame() while not frame.is_valid: if(params._stop.is_set()): return 'exit' frame = controller.frame() hands = frame.hands controller.set_policy(Leap.Controller.POLICY_IMAGES) while len(hands) == 0: if(params._stop.is_set()): return 'exit' frame = controller.frame() hands = frame.hands # time.sleep(1) # while True: # if(params._stop.is_set()): # return 'exit' # frame = controller.frame() # hands = frame.hands # if len(hands) > 0: # if(params._stop.is_set()): # return 'exit' # confidence_now = hands[0].confidence # display.update_confidence_label(confidence_now) # if confidence_now >= display.confidence: # break image = frame.images[0] d = {} d['utc'] = str(datetime.datetime.utcnow()) d['name'] = name d['gesture'] = gesture # print 'Confidence: ' + str(confidence_now) for hand in hands: if hand.is_valid: print 'Valid hand' if hand.is_right: which_hand = 'right_hand' else: which_hand = 'left_hand' hand_palm_position = hand.palm_position d[which_hand] = {} d[which_hand]['confidence'] = hand.confidence d[which_hand]['direction'] = (hand.direction-hand_palm_position).to_tuple() d[which_hand]['grab_strength'] = hand.grab_strength d[which_hand]['palm_normal'] = (hand.palm_normal-hand_palm_position).to_tuple() d[which_hand]['palm_position'] = (hand.palm_position-hand_palm_position).to_tuple() d[which_hand]['palm_velocity'] = hand.palm_velocity.to_tuple() d[which_hand]['palm_width'] = hand.palm_width d[which_hand]['sphere_center'] = (hand.sphere_center-hand_palm_position).to_tuple() d[which_hand]['sphere_radius'] = hand.sphere_radius d[which_hand]['stabilized_palm_position'] = (hand.stabilized_palm_position-hand_palm_position).to_tuple() arm = hand.arm d[which_hand]['arm'] = {} d[which_hand]['arm']['direction'] = arm.direction.to_tuple() d[which_hand]['arm']['elbow_position'] = (arm.elbow_position-hand_palm_position).to_tuple() d[which_hand]['arm']['wrist_position'] = (arm.wrist_position-hand_palm_position).to_tuple() fingers = hand.fingers for finger in fingers: if finger.type == Finger.TYPE_THUMB: which_finger = 'thumb' elif finger.type == Finger.TYPE_INDEX: which_finger = 'index' elif finger.type == Finger.TYPE_MIDDLE: which_finger = 'middle' elif finger.type == Finger.TYPE_RING: which_finger = 'ring' elif finger.type == Finger.TYPE_PINKY: which_finger = 'pinky' else: break d[which_hand][which_finger] = {} d[which_hand][which_finger]['direction'] = finger.direction.to_tuple() d[which_hand][which_finger]['length'] = finger.length d[which_hand][which_finger]['stabilized_tip_position'] = (finger.stabilized_tip_position-hand_palm_position).to_tuple() d[which_hand][which_finger]['tip_position'] = (finger.tip_position-hand_palm_position).to_tuple() d[which_hand][which_finger]['tip_velocity'] = finger.tip_velocity.to_tuple() d[which_hand][which_finger]['width'] = finger.width for i in range(4): bone = 'bone_' + str(i) d[which_hand][which_finger][bone] = {} d[which_hand][which_finger][bone]['center'] = (finger.bone(i).center-hand_palm_position).to_tuple() d[which_hand][which_finger][bone]['direction'] = finger.bone(i).direction.to_tuple() d[which_hand][which_finger][bone]['length'] = finger.bone(i).length d[which_hand][which_finger][bone]['width'] = finger.bone(i).width d[which_hand][which_finger][bone]['next_joint'] = (finger.bone(i).next_joint-hand_palm_position).to_tuple() d[which_hand][which_finger][bone]['prev_joint'] = (finger.bone(i).prev_joint-hand_palm_position).to_tuple() else: print 'Not a valid hand' ret = mongo.save(d, display.db_name, display.collection_name) if(ret.startswith('success')): [ret, oid] = ret.split(' ') if image.is_valid: print 'valid image' directory = os.path.join(os.getcwd(), 'images/') extension = '.png' tmp_file = 'tmp' + extension data = image.data barray = bytearray(image.width * image.height) for d in range(0, image.width * image.height - 1): barray[d] = data[d] img = Image.frombytes('L', (image.width, image.height), buffer(barray)) img.save(directory + tmp_file) img = io.imread(directory + tmp_file) thresh = filters.threshold_isodata(img) bw_img = img > thresh io.imsave(directory + oid + extension, util.img_as_ubyte(bw_img)) os.remove(directory + tmp_file) else: print 'invalid image' return ret + ' ' + oid + ' ' + display.db_name + ' ' + display.collection_name else: return ret
def create_slicemap_config(self): filter = self.filter_name slicemaps_paths = [] for i in range(0, self.slicemaps_number): slicemaps_paths.append( os.path.join( self.relative_path_to_slicemaps_dir, self.slicemap_name_format.format( i, self.row_col[0], self.row_col[1], int(self.slicemap_size[0]), int(self.slicemap_size[1]), self.filter_name, ), ) ) rows_cols = self.row_col slicemap_size = self.slicemap_size slices_range = self.slices_range original_slice_size = self.original_slice_size volume_size = [ self.area_of_slice[1][0] - self.area_of_slice[0][0], self.area_of_slice[1][1] - self.area_of_slice[0][1], self.slices_range[1] - self.slices_range[0], ] area_of_slice = [self.area_of_slice[0], self.area_of_slice[1]] slice_path_to_middle_slice = self.slices_path_list[int((self.slices_range[0] + self.slices_range[1]) / 2)] middle_slice = Image.open(slice_path_to_middle_slice) middle_slice_numpy_array = numpy.array(middle_slice) threshold_otsu_index = threshold_otsu(middle_slice_numpy_array) / 255.0 threshold_isodata_index = threshold_isodata(middle_slice_numpy_array) / 255.0 threshold_yen_index = threshold_yen(middle_slice_numpy_array) / 255.0 threshold_li_index = threshold_li(middle_slice_numpy_array) / 255.0 print("******************************************************************") print("Slicemap size: {0},{1} px".format(self.slicemap_size[0], self.slicemap_size[1])) print("Number of slicemaps: {0}".format(self.slicemaps_number)) print("Rows and cols: {0},{1}".format(rows_cols[0], rows_cols[1])) print("Number of slices: {0}".format(self.number_of_slices)) print( "Original slice size: {0},{1} px".format( int(self.original_slice_size[0]), int(self.original_slice_size[1]) ) ) print( "Slicemap slice size: {0},{1} px".format( int(self.slicemap_slice_size[0]), int(self.slicemap_slice_size[1]) ) ) print( "Proposional slicemap slice size: {0},{1} px".format( self.proposional_slicemap_slice_size[0], self.proposional_slicemap_slice_size[1] ) ) print("Volume proportions: {0},{1},{2}".format(volume_size[0], volume_size[1], volume_size[2])) print("Interpolation filter name: {0}".format(self.filter_name)) print("Number of rows and cols: {0},{1}".format(self.row_col[0], self.row_col[1])) print( "Global path to slicemaps: {0}".format( os.path.join( self.global_path_to_slicemaps_dir, self.slicemap_name_format.format( "n", self.row_col[0], self.row_col[1], int(self.slicemap_size[0]), int(self.slicemap_size[1]), self.filter_name, ), ) ) ) print( "Relative path to slicemaps: {0}".format( os.path.join( self.relative_path_to_slicemaps_dir, self.slicemap_name_format.format( "n", self.row_col[0], self.row_col[1], int(self.slicemap_size[0]), int(self.slicemap_size[1]), self.filter_name, ), ) ) ) print("Path to slices: {0}".format(self.path_to_slices)) print("Name of fisrt slice: {0}".format(self.files_list[0])) print( "Name of fisrt slicemaps: {0}".format( self.slicemap_name_format.format( 0, self.row_col[0], self.row_col[1], int(self.slicemap_size[0]), int(self.slicemap_size[1]), self.filter_name, ) ) ) print("Area_of_slice: {0},{1} px".format(self.area_of_slice[0], self.area_of_slice[1])) print("threshold_otsu_index: {0}".format(threshold_otsu_index)) print("threshold_isodata_index: {0}".format(threshold_isodata_index)) print("threshold_yen_index: {0}".format(threshold_yen_index)) print("threshold_li_index: {0}".format(threshold_li_index)) data = {} data["filter"] = self.filter_name data["slicemaps_paths"] = [] for i in range(0, self.slicemaps_number): data["slicemaps_paths"].append( os.path.join( self.relative_path_to_slicemaps_dir, self.slicemap_name_format.format( i, self.row_col[0], self.row_col[1], int(self.slicemap_size[0]), int(self.slicemap_size[1]), self.filter_name, ), ) ) data["row_col"] = rows_cols data["slicemap_size"] = slicemap_size data["slices_range"] = slices_range data["original_slice_size"] = original_slice_size data["slicemap_slice_size"] = self.slicemap_slice_size data["volume_size"] = volume_size data["area_of_slice"] = area_of_slice data["threshold_indexes"] = { "otsu": threshold_otsu_index, "isodata": threshold_isodata_index, "yen": threshold_yen_index, "li": threshold_li_index, } jsonString = json.dumps(data) print("************ CONFIG BEGIN ************ ") print(jsonString) print("************ CONFIG END ************** ") if not (os.path.exists(self.path_to_configs_dir)): os.makedirs(self.path_to_configs_dir) config_file = open(self.path_to_config, "w") config_file.write(jsonString) config_file.close()
matplotlib.rcParams['font.size'] = 9 img_orig = '/home/andrea/Desktop/20160713_NCP_GO_Talos_121.jpg' img_lowpass = '******' out_dir = '/home/andrea/Desktop/test' if not os.path.isdir(out_dir): os.makedirs(out_dir) os.chdir(out_dir) # print('Processing original') # image_orig = imread(img_orig, as_grey=True, flatten = True) # thresh_orig = threshold_isodata(image_orig) # binary_orig = image_orig > thresh_orig print('Processing lowpass isodata') image = imread(img_lowpass, as_grey=True, flatten = True) thresh_isodata = threshold_isodata(image) thresh_otsu = threshold_otsu(image) thresh_li = threshold_li(image) thresh_yen = threshold_yen(image) thresh_adaptive = threshold_adaptive(image, 3) binary_isodata = image > thresh_isodata binary_otsu = image > thresh_otsu binary_li = image > thresh_li binary_adaptive = image > thresh_adaptive binary_yen = image > thresh_yen # edges = canny(image_orig/255.) # fill_image = ndi.binary_fill_holes(edges) imshow(binary_isodata) imshow(binary_otsu) imshow(binary_yen) imshow(binary_li)