def _segment_trans(original_images, trans_args): """ Segmentation of objects :param original_images: :param transformation: :return: """ if len(original_images.shape) == 4: nb_images, img_rows, img_cols, nb_channels = original_images.shape else: nb_images, img_rows, img_cols = original_images.shape nb_channels = 1 segment_trans = trans_args.get('subtype').lower() transformed_images = [] if segment_trans == trans_utils.SEGMENT_TRANSFORMATIONS.GRADIENT.value: median_radius = trans_args.get('median_radius', 2) gradient_radius = trans_args.get('gradient_radius', 1) for img in original_images: # denoise image if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) denoised = rank.median(img, disk(median_radius)) img_trans = rank.gradient(denoised, disk(gradient_radius)) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif segment_trans == trans_utils.SEGMENT_TRANSFORMATIONS.WATERSHED.value: median_radius = trans_args.get('median_radius', 2) mark_radius = trans_args.get('mark_radius', 5) gradient_upper_bound = trans_args.get('gradient_upper_bound', 10) gradient_radius = trans_args.get('gradient_radius', 2) for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape((img_rows, img_cols)) # denoise image denoised = rank.median(img, disk(median_radius)) # find continuous region (low gradient - # where less than 10 for this image) --> markers markers = rank.gradient(denoised, disk(mark_radius)) < gradient_upper_bound markers = ndimage.label(markers)[0] # local gradient (disk(2) is used to keep edges thin) gradient = rank.gradient(denoised, disk(gradient_radius)) img = watershed(gradient, markers) if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) transformed_images.append(img) else: raise ValueError('{} is not supported.'.format(segment_trans)) # stack images transformed_images = np.stack(transformed_images, axis=0) if (nb_channels == 1): transformed_images = transformed_images.reshape( (nb_images, img_rows, img_cols, nb_channels)) return np.array(transformed_images)
def test_median_default_value(): a = np.zeros((3, 3), dtype=np.uint8) a[1] = 1 full_selem = np.ones((3, 3), dtype=np.uint8) assert_equal(rank.median(a), rank.median(a, full_selem)) assert rank.median(a)[1, 1] == 0 assert rank.median(a, disk(1))[1, 1] == 1
def test_median_default_value(self): a = np.zeros((3, 3), dtype=np.uint8) a[1] = 1 full_selem = np.ones((3, 3), dtype=np.uint8) assert_equal(rank.median(a), rank.median(a, full_selem)) assert rank.median(a)[1, 1] == 0 assert rank.median(a, disk(1))[1, 1] == 1
def labeling3(imghsv, hthres, cthres, size): h = imghsv[:, :, 0] # s=imghsv[:,:,1] v = imghsv[:, :, 2] # Filtering dh = rank.median(h, disk(3)) / 255.0 dv = rank.median(v, disk(3)) / 255.0 # np.max(dh) # hmax=np.percentile(h,95) hf = dh.copy() hf[(hf < hthres).astype(bool)] = 0 hf = hf / hthres # plt.imshow(hf) comb_r = hf * dv comb = opening(comb_r, selem=disk(3)) markers = np.zeros_like(comb) # Mark background markers[comb == 0] = 1 markers[comb > cthres] = 2 elevation_map = sobel(v) segmentation = watershed(elevation_map, markers) segmentation = ndi.binary_fill_holes(segmentation - 1) labeled_worms, _ = ndi.label(segmentation) for w in list(np.unique(labeled_worms)): # print labeled_worms[labeled_worms==w].shape[0] if labeled_worms[labeled_worms == w].shape[0] < size: labeled_worms[labeled_worms == w] = 0 return labeled_worms
def gaussiano(imagen,rgb,intensidad,unsolocolor,roj=None,ver=None,azu=None): if intensidad == True: dureza = 5 else: dureza = 3 if rgb == True: fil = imagen.copy() cont = 0 while cont < 3: fil[:,:,cont] = median(imagen[:,:,cont],diamond(dureza)) cont = cont +1 if unsolocolor == True: orig = imagen.copy() red = imagen[:,:,0] == roj green = imagen[:,:,1] == ver blue = imagen[:,:,2] == azu parte = red == green parte = parte == blue contraparte = ~parte seccion = fil.copy() resto = orig.copy() a = 0 while a < 3: seccion[:,:,a]=seccion[:,:,a]*parte resto[:,:,a]=resto[:,:,a]*contraparte a=a+1 final = resto+seccion else: final = fil else: final = median(imagen,diamond(dureza)) return final
def find_the_ball(nome): pasta = 'processing/img_recortadas/' im = io.imread(pasta + nome) im2 = im.copy() noisy_image = img_as_ubyte(im2[:,:,0]) noise = np.random.random(noisy_image.shape) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 im[:,:,0] = median(noisy_image, disk(1)) noisy_image = img_as_ubyte(im2[:,:,1]) noise = np.random.random(noisy_image.shape) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 im[:,:,1] = median(noisy_image, disk(1)) noisy_image = img_as_ubyte(im2[:,:,2]) noise = np.random.random(noisy_image.shape) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 im[:,:,2] = median(noisy_image, disk(1)) # Load picture and detect edges image = img_as_ubyte(im[:,:,0]) edges = canny(image, sigma=3, low_threshold=30, high_threshold=85) # Detect two radii hough_radii = np.arange(3, 15, 1) hough_res = hough_circle(edges, hough_radii) # Select the most prominent 3 circles accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=3) #mean = np.mean(im[cy[:],cx[:],], axis=1) # Draw them #_id = ball(mean, accums) #if(_id != -1): #accums, center_x, center_y, radius = accums[_id], cx[_id], cy[_id], radii[_id] for center_y, center_x, radius, ac in zip(cy, cx, radii, accums): #accums, center_x, center_y, radius = accums[0], cx[0], cy[0], radii[0] image = color.gray2rgb(image) circy, circx = circle(center_y, center_x, radius, shape=image.shape) #image[circy, circx] = 255 image = im if(image[circy, circx, :].mean() > 160 and image[circy, circx, :].mean() < 180 and ac > 0.55 and np.std(image[circy, circx, :]) > 20 and np.std(image[circy, circx, :]) < 45 ): print(nome +' - accums: ' +str(round(ac,2)) + ' - mean: '+ str(round(image[circy, circx, :].mean(),2))) image[circy, circx] = 255 io.imsave('img_ball/'+nome, (image).astype('uint8')) #plt.imshow(image, cmap=plt.cm.gray) #plt.show() circy, circx = circle_perimeter(center_y, center_x, radius, shape=image.shape) return center_y, center_x return -1,-1
def denoising_im(im): """ display denoise image This function remove noise on the input image Parameters ---------- im: float image Returns ---------- none (display is the output) Examples ---------- >>>denoising_im(muldrow) displays 4 set of images with plot size (22,7) with magnitude displayed by side >>>display_log(muldrow) displays log of image with default plot size (15,10) with no magnitude plot """ noisy_image = img_as_ubyte(im) noise = np.random.random(noisy_image.shape) noisy_image = img_as_ubyte(im) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 fig, ax = plt.subplots(2, 2, figsize=(10, 7), sharex=True, sharey=True) ax1, ax2, ax3, ax4 = ax.ravel() ax1.imshow(noisy_image, vmin=0, vmax=255, cmap=plt.cm.gray) ax1.set_title('Noisy image') ax1.axis('off') ax2.imshow(median(noisy_image, disk(1)), vmin=0, vmax=255, cmap=plt.cm.gray) ax2.set_title('Median $r=1$') ax2.axis('off') ax3.imshow(median(noisy_image, disk(5)), vmin=0, vmax=255, cmap=plt.cm.gray) ax3.set_title('Median $r=5$') ax3.axis('off') ax4.imshow(median(noisy_image, disk(20)), vmin=0, vmax=255, cmap=plt.cm.gray) ax4.set_title('Median $r=20$') ax4.axis('off')
def ad_blur(image): seed = random.random() if seed > 0.5: image = image / 127.5 - 1 image[:, :, 0] = median(image[:, :, 0], disk(3)) image[:, :, 1] = median(image[:, :, 1], disk(3)) image[:, :, 2] = median(image[:, :, 2], disk(3)) image = (image + 1) * 127.5 image = image.astype(np.uint8) return image
def show_img_median(): img = data.camera() # 3*3 and 5*5 滤波器 med1 = median(img, disk(3)) med2 = median(img, disk(5)) fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(15, 10)) ax1.imshow(img, cmap='gray') ax2.imshow(med1, cmap='gray') ax3.imshow(med2, cmap='gray') plt.show()
def transform(self, src): denoised = np.array([ rank.median(np.power(10, (src[0]) / 10.), morphology.disk(self.params['disk_radius'])), rank.median(np.power(10, (src[1]) / 10.), morphology.disk(self.params['disk_radius'])) ]) # find continuous region (low gradient - # where less than 10 for this image) --> markers # disk(5) is used here to get a more smooth image markers = np.array([ rank.gradient(denoised[0], disk(5)) < 10, rank.gradient(denoised[1], sk.morphology.disk(5)) < 10 ]) markers = ndi.label(markers)[0] # local gradient (disk(2) is used to keep edges thin) gradient = np.array([ rank.gradient(denoised[0], morphology.disk(self.params['disk_radius'])), rank.gradient(denoised[1], morphology.disk(self.params['disk_radius'])) ]) # process the watershed labels = np.array(morphology.watershed(gradient, markers), dtype='float') labels[np.isnan(src)] = np.NaN hist0 = np.histogram(labels[0].reshape(-1), bins=[1, 2, 3, 4, 5], normed=True, range=(0, self.params['max_range']))[0] hist1 = np.histogram(labels[1].reshape(-1), bins=[1, 2, 3, 4, 5], normed=True, range=(0, self.params['max_range']))[0] unique_labels = np.array(sorted(np.unique(labels))) unique_labels = unique_labels[~np.isnan(unique_labels)] label_means = {label: np.array([0, 0]) for label in range(int(7))} label_counts = {label: 0 for label in range(int(7))} label_idx = 0 for label in unique_labels: label_means[label_idx] = np.nanmean(src[labels == label].reshape( 2, -1), axis=1) label_counts[label_idx] = np.sum(~np.isnan(src[labels == label])) label_idx += 1 sorted_labels = sorted(label_counts.items(), key=lambda x: x[1])[::-1] label_vals0 = np.array( [label_means[label[0]][0] for label in sorted_labels]) label_vals1 = np.array( [label_means[label[0]][1] for label in sorted_labels]) return [label_vals0, label_vals1]
def test_percentile_median(): # check that percentile p0 = 0.5 is identical to local median img = data.camera() img16 = img.astype(np.uint16) selem = disk(15) # check for 8bit img_p0 = rank.percentile(img, selem=selem, p0=.5) img_max = rank.median(img, selem=selem) assert_equal(img_p0, img_max) # check for 16bit img_p0 = rank.percentile(img16, selem=selem, p0=.5) img_max = rank.median(img16, selem=selem) assert_equal(img_p0, img_max)
def test_percentile_median(): # check that percentile p0 = 0.5 is identical to local median img = data.camera() img16 = img.astype(np.uint16) selem = disk(15) # check for 8bit img_p0 = rank.percentile(img, selem=selem, p0=.5) img_max = rank.median(img, selem=selem) assert_equal(img_p0, img_max) # check for 16bit img_p0 = rank.percentile(img16, selem=selem, p0=.5) img_max = rank.median(img16, selem=selem) assert_equal(img_p0, img_max)
def run_main(): img = data.camera() med1 = median(img, disk(3)) med2 = median(img, disk(5)) fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(10, 5)) ax1.imshow(img, cmap='gray') ax2.imshow(med1, cmap='gray') ax3.imshow(med2, cmap='gray') plt.show() return ''
def segmentations(original_images, transformation): """ Segmentation of objects :param original_images: :param transformation: :return: """ nb_images, img_rows, img_cols, nb_channels = original_images.shape # TODO: checking number of channels and some customization for datasets # TODO: more variations, after testing is done transformed_images = [] if (transformation == TRANSFORMATION.seg_gradient): for img in original_images: # denoise image if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) denoised = rank.median(img, disk(2)) img_trans = rank.gradient(denoised, disk(1)) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.seg_watershed): for img in original_images: img = img.reshape((img_rows, img_cols)) # denoise image denoised = rank.median(img, disk(2)) # find continuous region (low gradient - # where less than 10 for this image) --> markers markers = rank.gradient(denoised, disk(5)) < 10 markers = ndimage.label(markers)[0] # local gradient (disk(2) is used to keep edges thin) gradient = rank.gradient(denoised, disk(2)) img_trans = watershed(gradient, markers) transformed_images.append(img_trans) else: raise ValueError('{} is not supported.'.format(transformation)) """ stack images """ transformed_images = np.stack(transformed_images, axis=0) if (nb_channels == 1): transformed_images = transformed_images.reshape( (nb_images, img_rows, img_cols, nb_channels)) return np.array(transformed_images)
def execute(input_image, settings): size = input_image.size size = (int(size[0] / 100), int(size[1] / 100)) grayscale = input_image.convert('L') image_arr = np.array(img_as_ubyte(grayscale)) denoised = rank.median(image_arr, disk(2)) markers = rank.gradient(denoised, disk(5)) < 10 markers = ndi.label(markers)[0] gradient = rank.gradient(denoised, disk(2)) labels = watershed(gradient, markers) figure = plt.figure(frameon=False) ax = plt.Axes(figure, [0., 0., 1., 1.]) ax.set_axis_off() figure.add_axes(ax) figure.set_size_inches(size) extent = mpl.transforms.Bbox(((0, 0), size)) ax.imshow(labels, cmap=plt.cm.spectral, interpolation='nearest') buffer = io.BytesIO() figure.savefig(buffer, bbox_inches=extent, pad_inches=0, format='png') buffer.seek(0) return Image.open(buffer)
def local_gradient(image, markers=None, connectivity=1, offset=None, mask=None, compactness=0, watershed_line=False): image = img_as_ubyte(image) denoised = rank.median(image, disk(2)) markers = rank.gradient(denoised, disk(5)) < 10 markers = ndi.label(markers)[0] gradient = rank.gradient(denoised, disk(2)) labels = watershed(gradient, markers) fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 8), sharex=True, sharey=True) ax = axes.ravel() ax[0].imshow(image, cmap=plt.cm.gray) ax[0].set_title("Original") ax[1].imshow(gradient, cmap=plt.cm.nipy_spectral) ax[1].set_title("Local Gradient") for a in ax: a.axis('off') fig.tight_layout() plt.show()
def process_image(img): img = rank.median(img, mp.disk(1)) p1, p99 = np.percentile(img, (1, 99)) img = rescale_intensity(img, in_range=(p1, p99)) img = mp.erosion(img) img = mp.erosion(img) img = mp.opening(img, mp.square(15)) img = mp.erosion(img) MIN = 0 MAX = 100 norm = ((img - MIN) / (MAX - MIN)) * 255 norm[norm > 255] = 255 norm[norm < 0] = 0 norm = mp.erosion(norm) norm = (norm > 100) * 255 elevation_map = filters.sobel(img) markers = np.zeros_like(img) markers[img < 5] = 1 markers[img > 200] = 2 img = mp.watershed(elevation_map, markers) mean_img = (img + norm / 255) / 2 if np.mean(np.array(mean_img[:, :])) < 1.4: img = norm img = img_as_ubyte(img) img = 1 - img contours = measure.find_contours(img, 1, fully_connected='high') return contours
def image_prep(img): # apply filters for better contrast and noise removal img_gamma = adjust_gamma(img, 0.7) img_median = median(img_gamma, disk(1)) # apply threshold val = threshold_otsu(img_median) img_otsu = img_median > val # label image regions label_image = label(img_otsu) candidates = [] for region in regionprops(label_image): minr, minc, maxr, maxc = region.bbox if (maxr - minr > maxc - minc): candidates.append(region) # find numbers areas = [] for candidate in candidates: areas.append(candidate.area) areas.sort() areas.reverse() n = 1 v = [] for candidate in candidates: if (candidate.area == areas[0] or candidate.area == areas[1] or candidate.area == areas[2]): v.append(candidate.image) imsave('num%d.png' % n, candidate.image) n += 1 return v
def gauss_filter(): ''' 对图片进行放大,然后进行高斯滤波,然后进行中值滤波 ''' gen = get_single_img_label() for img,label in gen: resize_img = resize_pic(img,[96,96]) gauss_img = filters.gaussian(resize_img,sigma=0.9) medium_img = rank.median(resize_img,selem=disk(3)) plt.figure() plt.subplot(2,2,1) plt.title('ori 28x28') plt.imshow(img) plt.subplot(2,2,2) plt.imshow(resize_img) plt.title('resize 96x96') plt.subplot(2, 2, 3) plt.imshow(gauss_img) plt.title('gauss filter') # plt.subplot(2, 2, 4) # plt.imshow(medium_img) plt.show()
def watershed(image): hsv_image = color.rgb2hsv(image) low_res_image = rescale(hsv_image[:, :, 0], SCALE) local_mean = mean(low_res_image, disk(50)) local_minimum_flat = np.argmin(local_mean) local_minimum = np.multiply(np.unravel_index(local_minimum_flat, low_res_image.shape), round(1 / SCALE)) certain_bone_pixels = np.full_like(hsv_image[:, :, 0], False, bool) certain_bone_pixels[ local_minimum[0] - INITIAL_WINDOW_SIZE/2:local_minimum[0]+INITIAL_WINDOW_SIZE/2, local_minimum[1] - INITIAL_WINDOW_SIZE/2:local_minimum[1]+INITIAL_WINDOW_SIZE/2 ] = True certain_non_bone_pixels = np.full_like(hsv_image[:, :, 0], False, bool) certain_non_bone_pixels[0:BORDER_SIZE, :] = True certain_non_bone_pixels[-BORDER_SIZE:-1, :] = True certain_non_bone_pixels[:, 0:BORDER_SIZE] = True certain_non_bone_pixels[:, -BORDER_SIZE:-1] = True smoothed_hsv = median(hsv_image[:, :, 0], disk(50)) threshold = MU * np.median(smoothed_hsv[certain_bone_pixels]) possible_bones = np.zeros_like(hsv_image[:, :, 0]) possible_bones[smoothed_hsv < threshold] = 1 markers = np.zeros_like(possible_bones) markers[certain_bone_pixels] = 1 markers[certain_non_bone_pixels] = 2 labels = morphology.watershed(-possible_bones, markers) return labels
def transform_image(self): # impacts what edge pixels we keep const_low_threshold = 200 #0.09 const_high_threshold = 300 #0.17 # impacts 'noise' reduction rate const_disk_radius = 2.5 # impacts how much we dilate the pixels const_dilation_steps = 20 if not os.path.isfile(self.img_fname): raise 'Image with filename ' + self.img_fname + ' not found!' # img_idx = os.path.splitext(os.path.basename(self.img_fname))[0] # print(img_idx) img = cv2.imread(self.img_fname, 0) canny_img = cv2.Canny(img, const_low_threshold, const_high_threshold) # cv2.imwrite('edges\\'+ img_idx +'_edge_image.jpg', canny_img) median_img = median(canny_img, disk(const_disk_radius)) # cv2.imwrite('medians\\'+ img_idx +'_median_image.jpg', median_img) dilated_img = median_img for j in range(const_dilation_steps): dilated_img = binary_dilation(dilated_img) # cv2.imwrite('dilations\\'+ img_idx +'_dilation_image.jpg', dilated_img*255) return dilated_img
def watershed(self,img,smoothen = 5,extrasmoothen=2,con_grad=10,plot=True): smoothImg = rank.median(img, disk(smoothen)) markers = rank.gradient(smoothImg, disk(smoothen)) < con_grad markers = ndi.label(markers)[0] gradient = rank.gradient(img, disk(extrasmoothen)) labels = watershed(gradient, markers) if plot==True: fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8), sharex=True, sharey=True) ax = axes.ravel() ax[0].imshow(img, cmap=plt.cm.gray) ax[0].set_title("Original") ax[1].imshow(gradient, cmap=plt.cm.nipy_spectral) ax[1].set_title("Local Gradient") ax[2].imshow(markers, cmap=plt.cm.nipy_spectral) ax[2].set_title("Markers") ax[3].imshow(img, cmap=plt.cm.gray) ax[3].imshow(labels, cmap=plt.cm.nipy_spectral, alpha=.7) ax[3].set_title("Segmented") for a in ax: a.axis('off') fig.tight_layout() plt.show() return labels
def _repair_bad_pixels_generic(raw, coords, method='median'): if median is None: raise RuntimeError('scikit-image is required for repair_bad_pixels if the Bayer pattern is not 2x2') color_masks = _colormasks(raw) rawimg = raw.raw_image_visible r = 5 kernel = np.ones((r,r)) for color_mask in color_masks: mask = np.zeros_like(color_mask) mask[coords[:,0],coords[:,1]] = True mask &= color_mask # interpolate all bad pixels belonging to this color if method == 'mean': # With mean filtering we have to ignore the bad pixels as they # would influence the mean too much. # FIXME could lead to invalid values if bad pixels are clustered # such that no valid pixels are left in a block raise NotImplementedError elif method == 'median': # bad pixels won't influence the median in most cases and just using # the color mask prevents bad pixel clusters from producing # bad interpolated values (NaNs) smooth = median(rawimg, kernel, mask=color_mask) else: raise ValueError rawimg[mask] = smooth[mask]
def median_image(image_array, windows_size, window_shape="square", im_show=True): """local median of an image. Parameters ---------- image_array:numpy.array: input image windows_size:int the size of window window_shape: str str is element from dict:{square, disk} im_show : Bool if True show result """ check_windows_size(windows_size) kernel = make_kernel(window_shape, windows_size) #median img = median(image_array, kernel) #show image if im_show: show_image(img)
def test_line_profile_dynamic(): """Test a line profile updating after an image transform""" image = data.coins()[:-50, :] # shave some off to make the line lower image = skimage.img_as_float(image) viewer = ImageViewer(image) lp = LineProfile(limits='dtype') viewer += lp line = lp.get_profiles()[-1][0] assert line.size == 129 assert_almost_equal(np.std(viewer.image), 0.208, 3) assert_almost_equal(np.std(line), 0.229, 3) assert_almost_equal(np.max(line) - np.min(line), 0.725, 1) # Matplotlib 2.2.3 seems to use np.asscalar which issues a warning # with numpy 1.16 # Matplotlib 2.2.3 is the last supported version for Python 2.7 with expected_warnings(['precision loss', r'np.asscalar|\A\Z']): viewer.image = skimage.img_as_float(median(image, selem=disk(radius=3))) line = lp.get_profiles()[-1][0] assert_almost_equal(np.std(viewer.image), 0.198, 3) assert_almost_equal(np.std(line), 0.220, 3) assert_almost_equal(np.max(line) - np.min(line), 0.639, 1)
def gen_salt_filter(): ''' 添加椒盐噪声然后使用中值滤波和均值滤波 ''' gen = get_single_img_label() for img,label in gen: img = util.random_noise(img, mode='salt') fil_camer = rank.median(img, selem=disk(3)) media_camer = rank.mean(img, selem=disk(3)) plt.figure() plt.subplot(2, 2, 1) plt.imshow(img) plt.title('add salt noise') plt.subplot(2, 2, 2) plt.imshow(fil_camer) plt.title('media filter') plt.subplot(2, 2, 3) plt.imshow(media_camer) plt.title('mean filter') plt.show()
def watershed(img): denoised = rank.median(img, morphology.disk(2)) markers = rank.gradient(denoised, morphology.disk(5)) < 10 markers = ndi.label(markers)[0] gradient = rank.gradient(denoised, morphology.disk(2)) labels = morphology.watershed(gradient, markers) fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8), sharex=True, sharey=True) ax = axes.ravel() ax[0].imshow(img, cmap=plt.cm.gray) ax[0].set_title("Original") ax[1].imshow(gradient, cmap=plt.cm.nipy_spectral) ax[1].set_title("Local Gradient") ax[2].imshow(markers, cmap=plt.cm.nipy_spectral) ax[2].set_title("Markers") ax[3].imshow(img, cmap=plt.cm.gray) ax[3].imshow(labels, cmap=plt.cm.nipy_spectral, alpha=.7) ax[3].set_title("Segmented") for a in ax: a.axis('off') fig.tight_layout() plt.show()
def _repair_bad_pixels_generic(raw, coords, method='median'): if median is None: raise RuntimeError( 'scikit-image is required for repair_bad_pixels if the Bayer pattern is not 2x2' ) color_masks = _colormasks(raw) rawimg = raw.raw_image_visible r = 5 kernel = np.ones((r, r)) for color_mask in color_masks: mask = np.zeros_like(color_mask) mask[coords[:, 0], coords[:, 1]] = True mask &= color_mask # interpolate all bad pixels belonging to this color if method == 'mean': # With mean filtering we have to ignore the bad pixels as they # would influence the mean too much. # FIXME could lead to invalid values if bad pixels are clustered # such that no valid pixels are left in a block raise NotImplementedError elif method == 'median': # bad pixels won't influence the median in most cases and just using # the color mask prevents bad pixel clusters from producing # bad interpolated values (NaNs) smooth = median(rawimg, kernel, mask=color_mask) else: raise ValueError rawimg[mask] = smooth[mask]
def get_frames(self, invert=False, denoise=False, dsk=None, inplace=True): if not self.video.isOpened(): raise IOError("Error opening the video file") else: frames = [] while self.video.isOpened(): ret, frame = self.video.read() if frame is None: print("Done reading video " + self.file) self.video.release() break else: frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) if invert: frame = cv.bitwise_not(frame) if denoise: if dsk is None: print("Using default disk value 2") dsk = 2 frame = rank.median(frame, disk(dsk)) frames.append(frame) print("Done reading frames for " + self.file) if inplace: self.frames = frames else: return frames
def _find_bad_pixel_candidates_generic(raw, isCandidateFn): if median is None: raise RuntimeError('scikit-image is required if the Bayer pattern is not 2x2') color_masks = _colormasks(raw) rawimg = raw.raw_image_visible coords = [] # median filtering for each channel r = 5 kernel = np.ones((r,r)) for mask in color_masks: # skimage's median is quite slow, it uses an O(r) filtering algorithm. # There exist O(log(r)) and O(1) algorithms, see https://nomis80.org/ctmf.pdf. # Also, we only need the median values for the masked pixels. # Currently, they are calculated for all pixels for each color. med = median(rawimg, kernel, mask=mask) # detect possible bad pixels candidates = isCandidateFn(rawimg, med) candidates &= mask y,x = np.nonzero(candidates) # note: the following is much faster than np.transpose((y,x)) candidates = np.empty((len(y),2), dtype=y.dtype) candidates[:,0] = y candidates[:,1] = x coords.append(candidates) return coords
def canny_filter(): ''' 对高斯滤波后的图像进行canny滤波 ''' gen = get_single_img_label() for img, label in gen: img = resize_pic(img, [96, 96]) gauss_img = filters.gaussian(img, sigma=0.9) medium_img = rank.median(gauss_img,selem=disk(3)) canny_img = feature.canny(gauss_img, sigma=3)*1 canny_img2 = feature.canny(medium_img,sigma=3)*1 canny_img = np.asanyarray(canny_img,dtype=np.float32) canny_img2 = np.asanyarray(canny_img2,dtype=np.float32) plt.figure() plt.subplot(2, 2, 1) plt.title(label) plt.imshow(canny_img2) plt.subplot(2, 2, 2) plt.imshow(gauss_img) plt.title('gauss_img') plt.subplot(2, 2, 3) plt.imshow(medium_img) plt.title('medium_img') plt.subplot(2, 2, 4) plt.imshow(canny_img) plt.title('canny_img') plt.show()
def median_filter(image, kernel_shape, kernel_size): """Apply a median filter to a 2-d image. Parameters ---------- image : np.ndarray, np.uint Image with shape (y, x). kernel_shape : str Shape of the kernel used to compute the filter ('diamond', 'disk', 'rectangle' or 'square'). kernel_size : int or Tuple(int) The size of the kernel. For the rectangle we expect two integers (width, height). Returns ------- image_filtered : np.ndarray, np.uint Filtered 2-d image with shape (y, x). """ # check parameters check_array(image, ndim=2, dtype=[np.uint8, np.uint16]) check_parameter(kernel_shape=str, kernel_size=(int, tuple, list)) # get kernel kernel = _define_kernel(shape=kernel_shape, size=kernel_size, dtype=image.dtype) # apply filter image_filtered = rank.median(image, kernel) return image_filtered
def _find_bad_pixel_candidates_generic(raw, isCandidateFn): if median is None: raise RuntimeError( 'scikit-image is required if the Bayer pattern is not 2x2') color_masks = _colormasks(raw) rawimg = raw.raw_image_visible coords = [] # median filtering for each channel r = 5 kernel = np.ones((r, r)) for mask in color_masks: # skimage's median is quite slow, it uses an O(r) filtering algorithm. # There exist O(log(r)) and O(1) algorithms, see https://nomis80.org/ctmf.pdf. # Also, we only need the median values for the masked pixels. # Currently, they are calculated for all pixels for each color. med = median(rawimg, kernel, mask=mask) # detect possible bad pixels candidates = isCandidateFn(rawimg, med) candidates &= mask y, x = np.nonzero(candidates) # note: the following is much faster than np.transpose((y,x)) candidates = np.empty((len(y), 2), dtype=y.dtype) candidates[:, 0] = y candidates[:, 1] = x coords.append(candidates) return coords
def watershed(img, k=5): import numpy as np from skimage.filters import rank from skimage.morphology import watershed, disk from scipy import ndimage as ndi # analizamos el gradiente canal por canal # remover ruido denoised = img.copy() gradient4markers = img.copy() gradient4watershed = img.copy() for i in range(img.shape[-1]): # -> float para que los gradientes sean suaves denoised[..., i] = rank.median(img[..., i], disk(3)).astype('float') gradient4markers[..., i] = rank.gradient(denoised[..., i], disk(5)) gradient4watershed[..., i] = rank.gradient(denoised[..., i], disk(2)) # agregamos los gradientes de cada canal (promedio) gradient4markers = np.mean(gradient4markers, axis=2) gradient4watershed = np.mean(gradient4watershed, axis=2) # definimos marcadores como zonas de bajo gradiente relativo markers = gradient4markers <= np.percentile(gradient4markers, q=0.1) markers = ndi.label(markers)[0] # admitimos un maximo de k clusters; tomar los k mas grandes if np.max(markers) > k: marker_labels = np.unique(markers[markers > 0]) sizes = np.array([np.sum(markers == i) for i in marker_labels]) labels_sorted = marker_labels[sizes.argsort()[::-1]] labels_retained = labels_sorted[0:k] markers[np.logical_not(np.isin(markers, labels_retained))] = 0 # process the watershed labels = watershed(gradient4watershed, markers) return (labels)
def _threshold_hs(img_np): '''Performs thresholding on the WSI image to extract the tissue region. RGB image is converted to HSV color space. The H and S channels are then thresholded via Otsu's Threshold, then combined via bitwise AND. Morphological transormation was applied by removing small holes and regions, and was filtered using median blur. Parameters ---------- img_np: np.uint8[H, W, 3] np.array RGB WSI as an np.array image Returns ------- bool[H, W] np.array ROI mask of the WSI. ''' img_hsv = rgb2hsv(img_np) channel_h = img_hsv[:, :, 0] channel_s = img_hsv[:, :, 1] thresh_h = threshold_otsu(channel_h) thresh_s = threshold_otsu(channel_s) binary_h = channel_h > thresh_h binary_s = channel_s > thresh_s binary = np.bitwise_and(binary_h, binary_s) binary = morphology.remove_small_objects(binary, _SMALL_OBJECT_AREA) binary = morphology.remove_small_holes(binary, _SMALL_HOLE_AREA) binary = median(binary, morphology.disk(_MEDIAN_DISK)) return binary.astype(bool)
def _threshold_gray(img_np): binary = np.full(img_np.shape[:2], False) binary[np.where(rgb2gray(img_np) < 0.8)] = True binary = morphology.remove_small_objects(binary, _SMALL_OBJECT_AREA) binary = morphology.remove_small_holes(binary, _SMALL_HOLE_AREA) binary = median(binary, morphology.disk(_MEDIAN_DISK)) return binary
def preproc_2d_img(img): #silence Possible precision loss when converting from float64 to uint8 warning with warnings.catch_warnings(): warnings.simplefilter("ignore") picture = np.rot90(img) picture /= np.max(picture) # apply median filter to make stripes more vissible picture = median(picture, disk(1)) return picture
def smooth(self): # TODO: there is non nan in the ff img, or? mask = self.flatField == 0 from skimage.filters.rank import median, mean from skimage.morphology import disk ff = mean(median(self.flatField, disk(5), mask=~mask), disk(13), mask=~mask) return ff.astype(float) / ff.max(), mask
def label_from_thresh(frame, thresh, parameters): smooth = parameters['smooth'] min_distance = np.int(parameters['nuc_distance']) image = rank.median(frame, disk(smooth)) image = rank.enhance_contrast(image, disk(smooth)) im_max = image.max() if im_max < thresh: return np.zeros(image.shape, dtype=np.int32) else: image = image > thresh distance = ndimage.distance_transform_edt(image) local_maxi = peak_local_max(distance, footprint=disk(min_distance), #min_distance=min_distance, indices=False, labels=image) markers = ndimage.label(local_maxi)[0] return watershed(-distance, markers, mask=image)
def compactness(_img): ## Lookup table for the empirical distribution of median(img)/img ## in the case of a random image (white noise), for varying ## proportions of white pixels in the image (0.1, 0.2, ..., 1.0). ## The distributions are approximated by Gaussians, and the ## corresponding means and standard deviations are stored. prop = np.linspace(0.1, 1.0, 10) emp_distrib_mean = np.array([4.4216484763437432e-06, 0.0011018116582350559, 0.042247116747488218, 0.34893587605251208, 1.0046008733628913, 1.4397675817057451, 1.4115741958770296, 1.2497935146232551, 1.1111058415275834, 1.0]) emp_distrib_std = np.array([2.7360459073474441e-05, 0.00051125394394966434, 0.0038856377648490894, 0.012029872915543046, 0.013957075037020938, 0.0057246251730834283, 0.0028750796874699143, 0.0023709207886137384, 0.0015018959493632007, 0.0]) if _img.ndim != 2: raise ValueError('The input image must be a 2D binary image.') _img = (_img != 0).astype(np.uint8) _med = median(_img, disk(3)) # "proportion of white pixels" in the image: swp = np.sum(_img, dtype=np.float64) pwp = swp / _img.size # compactness coefficient cf = np.sum(_med, dtype=np.float64) / swp # standardize using the "closest" Gaussian from the list of empirical # distributions: k = np.argmin(np.abs(prop - pwp)) # this should make the coeff more or less normally distributed N(0,1) cf = (cf - emp_distrib_mean[k]) / emp_distrib_std[k] return cf
def test_line_profile_dynamic(): """Test a line profile updating after an image transform""" image = data.coins()[:-50, :] # shave some off to make the line lower image = skimage.img_as_float(image) viewer = ImageViewer(image) lp = LineProfile(limits='dtype') viewer += lp line = lp.get_profiles()[-1][0] assert line.size == 129 assert_almost_equal(np.std(viewer.image), 0.208, 3) assert_almost_equal(np.std(line), 0.229, 3) assert_almost_equal(np.max(line) - np.min(line), 0.725, 1) viewer.image = skimage.img_as_float(median(image, selem=disk(radius=3))) line = lp.get_profiles()[-1][0] assert_almost_equal(np.std(viewer.image), 0.198, 3) assert_almost_equal(np.std(line), 0.220, 3) assert_almost_equal(np.max(line) - np.min(line), 0.639, 1)
def check_all(): np.random.seed(0) image = np.random.rand(25, 25) selem = morphology.disk(1) refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz")) assert_equal(refs["autolevel"], rank.autolevel(image, selem)) assert_equal(refs["autolevel_percentile"], rank.autolevel_percentile(image, selem)) assert_equal(refs["bottomhat"], rank.bottomhat(image, selem)) assert_equal(refs["equalize"], rank.equalize(image, selem)) assert_equal(refs["gradient"], rank.gradient(image, selem)) assert_equal(refs["gradient_percentile"], rank.gradient_percentile(image, selem)) assert_equal(refs["maximum"], rank.maximum(image, selem)) assert_equal(refs["mean"], rank.mean(image, selem)) assert_equal(refs["mean_percentile"], rank.mean_percentile(image, selem)) assert_equal(refs["mean_bilateral"], rank.mean_bilateral(image, selem)) assert_equal(refs["subtract_mean"], rank.subtract_mean(image, selem)) assert_equal(refs["subtract_mean_percentile"], rank.subtract_mean_percentile(image, selem)) assert_equal(refs["median"], rank.median(image, selem)) assert_equal(refs["minimum"], rank.minimum(image, selem)) assert_equal(refs["modal"], rank.modal(image, selem)) assert_equal(refs["enhance_contrast"], rank.enhance_contrast(image, selem)) assert_equal(refs["enhance_contrast_percentile"], rank.enhance_contrast_percentile(image, selem)) assert_equal(refs["pop"], rank.pop(image, selem)) assert_equal(refs["pop_percentile"], rank.pop_percentile(image, selem)) assert_equal(refs["pop_bilateral"], rank.pop_bilateral(image, selem)) assert_equal(refs["sum"], rank.sum(image, selem)) assert_equal(refs["sum_bilateral"], rank.sum_bilateral(image, selem)) assert_equal(refs["sum_percentile"], rank.sum_percentile(image, selem)) assert_equal(refs["threshold"], rank.threshold(image, selem)) assert_equal(refs["threshold_percentile"], rank.threshold_percentile(image, selem)) assert_equal(refs["tophat"], rank.tophat(image, selem)) assert_equal(refs["noise_filter"], rank.noise_filter(image, selem)) assert_equal(refs["entropy"], rank.entropy(image, selem)) assert_equal(refs["otsu"], rank.otsu(image, selem)) assert_equal(refs["percentile"], rank.percentile(image, selem)) assert_equal(refs["windowed_histogram"], rank.windowed_histogram(image, selem))
def background_subtraction(self, img, method='avg'): #width, height = img.shape if method=='avg': # vigra #kernel = vigra.filters.averagingKernel(radius) #bgsub = img - vigra.filters.convolve(self.ut.to_float(img), kernel) # with skimage se = disk(self.settings.background_subtraction['radius']) bgsub = img.astype(np.dtype('float')) - rank.mean(img, se) bgsub[bgsub < 0] = 0 bgsub = bgsub.astype(img.dtype) if method=='med': # vigra #kernel = vigra.filters.averagingKernel(radius) #bgsub = img - vigra.filters.convolve(self.ut.to_float(img), kernel) # with skimage se = disk(self.settings.background_subtraction['radius']) bgsub = img.astype(np.dtype('float')) - rank.median(img, se) bgsub[bgsub < 0] = 0 bgsub = bgsub.astype(img.dtype) elif method=='constant_median': # vigra #bgsub = img - np.median(np.array(img)) # with skimage bgsub = img - np.median(img) bgsub[bgsub < 0] = 0 bgsub = bgsub.astype(img.dtype) return bgsub
def generate(): np.random.seed(None) ohe = OneHotEncoder(sparse=False) hmap = np.array(DS.diamond_square((200, 200), -1, 1, 0.35)) + np.array(DS.diamond_square((200, 200), -1, 1, 0.55)) + np.array(DS.diamond_square((200, 200), -1, 1, 0.75)) hmap_flatten = np.array(hmap).ravel()[:, None] kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(hmap_flatten) labels_hmap = kmeans.predict(hmap_flatten)[:, None] # Back to rectangular labels_hmap = labels_hmap.reshape([hmap.shape[0], hmap.shape[1]]) labels_hmap = median(labels_hmap.astype(np.uint8), disk(5)) labels_hmap = resize(labels_hmap, dims, order=0, preserve_range=True) labels_hmap = ohe.fit_transform(labels_hmap.ravel()[:, None]) # Reshape hmap_masks = labels_hmap.reshape([dims[0], dims[1], n_colors]) hmap_masks = hmap_masks.transpose([2, 0, 1]) return hmap_masks
def cr_med(image, selem): return median(image=image, selem=selem)
from skimage.morphology import disk noise = np.random.random(noisy_image.shape) noisy_image = img_as_ubyte(data.camera()) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 fig, ax = plt.subplots(2, 2, figsize=(10, 7), sharex=True, sharey=True) ax1, ax2, ax3, ax4 = ax.ravel() ax1.imshow(noisy_image, vmin=0, vmax=255, cmap=plt.cm.gray) ax1.set_title('Noisy image') ax1.axis('off') ax1.set_adjustable('box-forced') ax2.imshow(median(noisy_image, disk(1)), vmin=0, vmax=255, cmap=plt.cm.gray) ax2.set_title('Median $r=1$') ax2.axis('off') ax2.set_adjustable('box-forced') ax3.imshow(median(noisy_image, disk(5)), vmin=0, vmax=255, cmap=plt.cm.gray) ax3.set_title('Median $r=5$') ax3.axis('off') ax3.set_adjustable('box-forced') ax4.imshow(median(noisy_image, disk(20)), vmin=0, vmax=255, cmap=plt.cm.gray) ax4.set_title('Median $r=20$') ax4.axis('off') ax4.set_adjustable('box-forced')
#zmiana rozdzielczosci rows, cols = img.shape im = Image.fromarray(img) im = im.resize((processing_height*cols/rows,processing_height), Image.ANTIALIAS) img = np.array(im) rows, cols = img.shape img2=np.uint8(img*255) img = (1-img) global_thresh = threshold_otsu(img) img = img > global_thresh img = np.uint8(img) #wykrywanie obramowania img2 = rank.median(img2, np.ones([5,5],dtype=np.float64)) para2=120 circles = cv2.HoughCircles(img2,cv.CV_HOUGH_GRADIENT,1,100, param1=30,\ param2=para2,minRadius=100,maxRadius=250) while circles==None and para2>0: para2-=2 circles = cv2.HoughCircles(img2,cv.CV_HOUGH_GRADIENT,1,100, param1=30,\ param2=para2,minRadius=100,maxRadius=250) cirx=circles[0][0][0] ciry=circles[0][0][1] cirr=circles[0][0][2] if cirx+cirr>cols: cirr=rows-cirx if cirx-cirr<0: cirr=cirx if ciry+cirr>rows: cirr=cols-ciry
def median_filter(image, radius): return median(image, selem=disk(radius))
def median_hsv(image, selem): return median(image, selem)
def median_each(image, selem): return median(image, selem)
def func(frame): smoothed = rank.median(frame,disk(smooth_size)) smoothed = rank.enhance_contrast(smoothed, disk(smooth_size)) return smoothed
""" from scipy import ndimage as ndi import matplotlib.pyplot as plt from skimage.morphology import watershed, disk from skimage import data from skimage.filters import rank from skimage.util import img_as_ubyte image = img_as_ubyte(data.camera()) # denoise image denoised = rank.median(image, disk(2)) # find continuous region (low gradient - # where less than 10 for this image) --> markers # disk(5) is used here to get a more smooth image markers = rank.gradient(denoised, disk(5)) < 10 markers = ndi.label(markers)[0] # local gradient (disk(2) is used to keep edges thin) gradient = rank.gradient(denoised, disk(2)) # process the watershed labels = watershed(gradient, markers) # display results fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8),
def filter2(image): med = median(image, disk(5)) return med
def transform(self, images): from skimage.filters.rank import median from skimage.morphology import disk return np.array([median(image, disk(self._radius)) for image in images])
p.exposure_equalization(method="equal") p.convert_color("RGB","HSV") p.save_current_as("structure") p.reset() p.scale_image(mask_scale) p.exposure_equalization(method="equal") p.convert_color("RGB","HSV") p.save_current_as("mask") # Load images for mask and structure information img2 = p.get_version("mask")[:,:,0] img = p.get_version("structure")[:,:,2] print("Masking") med_img = median(img2, disk(50*mask_scale)) mask = np.zeros(img2.shape) mask[med_img>np.mean(med_img)] = 1 mask_c = closing(mask, disk(100*mask_scale)) # plot_comparison(mask, mask_c, 'closing') # plot_comparison(mask_c, mean(mask_c, disk(20)), 'mean') masked = np.copy(img) # masked = img * resize(mask_c, img.shape) # plot_comparison(img, masked, "masked") print("bottomhatting") streets_2 = bottomhat(masked, disk(20*scale_factor)) # streets_3 = bottomhat(masked, disk(6))
def prefilter(self, img, method='median'): ps = self.settings.prefilter_settings[method] print print 'prefiltering :', method if method=='median': radius = ps['median_size'] # with vigra #filtered= vigra.filters.discMedian(img, radius) # with skimage pref = rank.median(img, disk(radius)) elif method=='avg': # with skimage se = disk(ps['avg_size']) pref = rank.mean(img, se) elif method=='bilateral': # with skimage se = disk(ps['bil_radius']) pref = rank.mean_bilateral(img, se, s0=ps['bil_lower'], s1=ps['bil_upper']) elif method=='denoise_bilateral': #skimage.filters.denoise_bilateral(image, win_size=5, sigma_range=None, sigma_spatial=1, pref = restoration.denoise_bilateral(img, ps['win_size'], ps['sigma_signal'], ps['sigma_space'], ps['bins'], mode='constant', cval=0, multichannel=False) elif method=='close_rec': se = disk(ps['close_size']) dil = morphology.dilation(img, se) rec = morphology.reconstruction(dil, img, method='erosion') # reconstruction gives back a float image (for whatever reason). pref = rec.astype(dil.dtype) elif method=='denbi_clorec': temp = restoration.denoise_bilateral(img, ps['win_size'], ps['sigma_signal'], ps['sigma_space'], ps['bins'], mode='constant', cval=0, multichannel=False) temp = 255 * temp temp = temp.astype(img.dtype) se = disk(ps['close_size']) dil = morphology.dilation(temp, se) rec = morphology.reconstruction(dil, temp, method='erosion') # reconstruction gives back a float image (for whatever reason). pref = rec.astype(img.dtype) elif method=='denbi_asfrec': temp = restoration.denoise_bilateral(img, ps['win_size'], ps['sigma_signal'], ps['sigma_space'], ps['bins'], mode='constant', cval=0, multichannel=False) temp = 255 * temp temp = temp.astype(img.dtype) se = disk(ps['close_size']) dil = morphology.dilation(temp, se) rec = morphology.reconstruction(dil, temp, method='erosion') se = disk(ps['open_size']) ero = morphology.erosion(rec, se) rec2 = morphology.reconstruction(ero, rec, method='dilation') # reconstruction gives back a float image (for whatever reason). pref = rec2.astype(img.dtype) elif method=='med_denbi_asfrec': if ps['median_size'] > 1: radius = ps['median_size'] pref = rank.median(img, disk(radius)) else: pref = img temp = restoration.denoise_bilateral(pref, ps['win_size'], ps['sigma_signal'], ps['sigma_space'], ps['bins'], mode='constant', cval=0, multichannel=False) temp = 255 * temp temp = temp.astype(img.dtype) if ps['close_size'] > 0 : se = disk(ps['close_size']) dil = morphology.dilation(temp, se) rec = morphology.reconstruction(dil, temp, method='erosion') else: rec = temp if ps['open_size'] > 0: se = disk(ps['open_size']) ero = morphology.erosion(rec, se) rec2 = morphology.reconstruction(ero, rec, method='dilation') else: rec2 = rec # reconstruction gives back a float image (for whatever reason). pref = rec2.astype(img.dtype) return pref
# Threshold value, as obtained by eye thresh_phase1 = 0.4 thresh_phase = 0.2 # Generate thresholded image im_phase_2 = subtracted2 > thresh_phase1 im_phase_1 = subtracted1 > thresh_phase # Display phase and thresholded image fig, ax = plt.subplots(1, 2, figsize=(10, 5)) ax[0].imshow(subtracted2, cmap=plt.cm.gray) ax[1].imshow(im_phase_2, cmap=plt.cm.gray) #fig, ax = plt.subplots(1, 2, figsize=(10, 5)) #ax[0].imshow(subtracted1, cmap=plt.cm.gray) #ax[1].imshow(im_phase_1, cmap=plt.cm.gray) from skimage.morphology import disk from skimage.filters.rank import median med2 = median(im_phase_2, disk(0.7)) inv_med2 = np.invert(med2) fig, ax = plt.subplots(1, 2, figsize=(10, 5)) ax[1].imshow(med2, cmap=plt.cm.gray) #ax[0].imshow(im_phase_2, cmap=plt.cm.gray) ax[0].imshow(inv_med2, cmap=plt.cm.gray)
''' import matplotlib.pyplot as plt from skimage import * from skimage.filters.rank import median from skimage.morphology import disk #from skimage.io import * from skimage import data import numpy as np from PIL import Image noisy_image = img_as_ubyte(data.imread('Ns.jpg', True)) noise = np.random.random(noisy_image.shape) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 im = Image.fromarray(median(noisy_image, disk(3))) im.save('3.jpg') ''' fig, ax = plt.subplots(2, 2, figsize=(10, 7), sharex=True, sharey=True) ax1, ax2, ax3, ax4 = ax.ravel() ax1.imshow(noisy_image, vmin=0, vmax=255, cmap=plt.cm.gray) ax1.set_title('Noisy image') ax1.axis('off') ax1.set_adjustable('box-forced') ax2.imshow(median(noisy_image, disk(1)), vmin=0, vmax=255, cmap=plt.cm.gray) ax2.set_title('Median $r=1$') ax2.axis('off') ax2.set_adjustable('box-forced')
from skimage.morphology import disk noise = np.random.random(noisy_image.shape) noisy_image = img_as_ubyte(data.camera()) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 fig, axes = plt.subplots(2, 2, figsize=(10, 7), sharex=True, sharey=True) ax = axes.ravel() ax[0].imshow(noisy_image, vmin=0, vmax=255, cmap=plt.cm.gray) ax[0].set_title('Noisy image') ax[0].axis('off') ax[0].set_adjustable('box-forced') ax[1].imshow(median(noisy_image, disk(1)), vmin=0, vmax=255, cmap=plt.cm.gray) ax[1].set_title('Median $r=1$') ax[1].axis('off') ax[1].set_adjustable('box-forced') ax[2].imshow(median(noisy_image, disk(5)), vmin=0, vmax=255, cmap=plt.cm.gray) ax[2].set_title('Median $r=5$') ax[2].axis('off') ax[2].set_adjustable('box-forced') ax[3].imshow(median(noisy_image, disk(20)), vmin=0, vmax=255, cmap=plt.cm.gray) ax[3].set_title('Median $r=20$') ax[3].axis('off') ax[3].set_adjustable('box-forced')
def median_filter(img, radius=3): with expected_warnings(['precision loss']): return median(img, selem=disk(radius=radius))