def test_2d_linearity(): a_black = np.ones((3, 3)).astype(np.uint8) a_white = invert(a_black) assert_allclose(meijering(1 * a_black, black_ridges=True), meijering(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(meijering(1 * a_white, black_ridges=False), meijering(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(sato(1 * a_black, black_ridges=True), sato(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(sato(1 * a_white, black_ridges=False), sato(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(frangi(1 * a_black, black_ridges=True), frangi(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(frangi(1 * a_white, black_ridges=False), frangi(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(hessian(1 * a_black, black_ridges=True), hessian(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(hessian(1 * a_white, black_ridges=False), hessian(10 * a_white, black_ridges=False), atol=1e-3)
def test_3d_energy_decrease(): a_black = np.zeros((5, 5, 5)).astype(np.uint8) a_black[2, 2, 2] = 255 a_white = invert(a_black) assert_array_less( meijering(a_black, black_ridges=True).std(), a_black.std()) assert_array_less( meijering(a_white, black_ridges=False).std(), a_white.std()) assert_array_less( sato(a_black, black_ridges=True, mode='reflect').std(), a_black.std()) assert_array_less( sato(a_white, black_ridges=False, mode='reflect').std(), a_white.std()) assert_array_less(frangi(a_black, black_ridges=True).std(), a_black.std()) assert_array_less(frangi(a_white, black_ridges=False).std(), a_white.std()) assert_array_less( hessian(a_black, black_ridges=True, mode='reflect').std(), a_black.std()) assert_array_less( hessian(a_white, black_ridges=False, mode='reflect').std(), a_white.std())
def test_3d_linearity(): # Note: last axis intentionally not size 3 to avoid 2D+RGB autodetection # warning from an internal call to `skimage.filters.gaussian`. a_black = np.ones((3, 3, 5)).astype(np.uint8) a_white = invert(a_black) assert_allclose(meijering(1 * a_black, black_ridges=True), meijering(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(meijering(1 * a_white, black_ridges=False), meijering(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(sato(1 * a_black, black_ridges=True, mode='reflect'), sato(10 * a_black, black_ridges=True, mode='reflect'), atol=1e-3) assert_allclose(sato(1 * a_white, black_ridges=False, mode='reflect'), sato(10 * a_white, black_ridges=False, mode='reflect'), atol=1e-3) assert_allclose(frangi(1 * a_black, black_ridges=True), frangi(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(frangi(1 * a_white, black_ridges=False), frangi(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(hessian(1 * a_black, black_ridges=True, mode='reflect'), hessian(10 * a_black, black_ridges=True, mode='reflect'), atol=1e-3) assert_allclose(hessian(1 * a_white, black_ridges=False, mode='reflect'), hessian(10 * a_white, black_ridges=False, mode='reflect'), atol=1e-3)
def test_cropped_camera_image(): image = crop(camera(), ((206, 206), (206, 206))) assert_allclose(frangi(image), np.zeros((100, 100)), atol=1e-03) assert_allclose(frangi(image, black_ridges=True), np.zeros((100, 100)), atol=1e-03) assert_allclose(hessian(image), np.ones((100, 100)), atol=1 - 1e-07)
def run(self, ips, imgs, para=None): imgs[:] = hessian(imgs, range(para['start'], para['end'], para['step']), alpha=para['alpha'], beta=para['beta'], gamma=para['gamma'], black_ridges=para['bridges'])
def hessianFiltering(image, fileprefix): # img must be read with skimg image_f = hessian(image, sigmas=[1, 1.5], black_ridges=False) final_image = np.multiply(image_f, image).astype(np.uint8) imageio.imwrite(f'{fileprefix}_hessian_filtered.png', final_image) image = cv2.imread(f'{fileprefix}_hessian_filtered.png', 0) return cv2.imread(f'{fileprefix}_hessian_filtered.png', 0)
def extract_vessels(img_orig): kernel = np.ones((2, 2), np.uint8) #kernel for erosion and dilation image = (hessian(img_orig) * 255).astype('uint8') #ridge detection image = remove_small_objects(image.astype(bool), min_size=64, connectivity=0).astype(float) image = cv2.dilate(image, kernel, iterations=3) #to join disconnected image = cv2.erode(image, kernel, iterations=3) #to join disconnected image = cv2.dilate(image, kernel, iterations=1) #to join disconnected image = cv2.erode(image, kernel, iterations=1) #to join disconnected image = cv2.dilate(image, kernel, iterations=1) #to join disconnected #Use any one below skel = skeletonize(image) # skel = thin(image) # med, distance = medial_axis(image, return_distance=True) # # skel = med*distance #To get the circular part mask = np.zeros_like(image, np.uint8) H, W = image.shape mask = cv2.circle(mask, (H // 2, W // 2), H // 2, (255, 255, 255), thickness=-1) masked_data = cv2.bitwise_and(skel * 255, skel * 255, mask=mask) return masked_data
def run(self, ips, snap, img, para=None): rst = hessian(snap, range(para['start'], para['end'], para['step']), alpha=para['alpha'], beta=para['beta'], gamma=para['gamma'], black_ridges=para['bridges']) img[:] = scale(rst, ips.range[0], ips.range[1])
def run(self, ips, imgs, para=None): IPy.show_img( hessian(imgs, range(para['start'], para['end'], para['step']), alpha=para['alpha'], beta=para['beta'], gamma=para['gamma'], black_ridges=para['bridges']), ips.title + '-hessian')
def apply(self, c): if self.filter_name == "frangi": return frangi(c) if self.filter_name == "hessian": return hessian(c) if self.filter_name == "sato": return sato(c) raise ValueError("FilterName - {} - not known".format( self.filter_name))
def test_2d_null_matrix(): a_black = np.zeros((3, 3)).astype(np.uint8) a_white = invert(a_black) zeros = np.zeros((3, 3)) ones = np.ones((3, 3)) assert_equal(meijering(a_black, black_ridges=True), ones) assert_equal(meijering(a_white, black_ridges=False), ones) assert_equal(sato(a_black, black_ridges=True), zeros) assert_equal(sato(a_white, black_ridges=False), zeros) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_equal(hessian(a_black, black_ridges=False), ones) assert_equal(hessian(a_white, black_ridges=True), ones)
def test_2d_cropped_camera_image(): a_black = crop(camera(), ((206, 206), (206, 206))) a_white = invert(a_black) zeros = np.zeros((100, 100)) ones = np.ones((100, 100)) assert_allclose(meijering(a_black, black_ridges=True), meijering(a_white, black_ridges=False)) assert_allclose(sato(a_black, black_ridges=True), sato(a_white, black_ridges=False)) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_allclose(hessian(a_black, black_ridges=True), ones, atol=1 - 1e-7) assert_allclose(hessian(a_white, black_ridges=False), ones, atol=1 - 1e-7)
def test_3d_null_matrix(): # Note: last axis intentionally not size 3 to avoid 2D+RGB autodetection # warning from an internal call to `skimage.filters.gaussian`. a_black = np.zeros((3, 3, 5)).astype(np.uint8) a_white = invert(a_black) zeros = np.zeros((3, 3, 5)) ones = np.ones((3, 3, 5)) assert_allclose(meijering(a_black, black_ridges=True), zeros, atol=1e-1) assert_allclose(meijering(a_white, black_ridges=False), zeros, atol=1e-1) assert_equal(sato(a_black, black_ridges=True, mode='reflect'), zeros) assert_equal(sato(a_white, black_ridges=False, mode='reflect'), zeros) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_equal(hessian(a_black, black_ridges=False, mode='reflect'), ones) assert_equal(hessian(a_white, black_ridges=True, mode='reflect'), ones)
def test_3d_cropped_camera_image(): a_black = crop(camera(), ((200, 212), (100, 312))) a_black = np.dstack([a_black, a_black, a_black]) a_white = invert(a_black) zeros = np.zeros((100, 100, 3)) ones = np.ones((100, 100, 3)) assert_allclose(meijering(a_black, black_ridges=True), meijering(a_white, black_ridges=False)) assert_allclose(sato(a_black, black_ridges=True, mode='reflect'), sato(a_white, black_ridges=False, mode='reflect')) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_allclose(hessian(a_black, black_ridges=True, mode='reflect'), ones, atol=1 - 1e-7) assert_allclose(hessian(a_white, black_ridges=False, mode='reflect'), ones, atol=1 - 1e-7)
def HHF(image): horizontal_gradient = sobel_h(image) hessian_filter = hessian(horizontal_gradient, scale_range=(1, 10), scale_step=2, beta1=0.5, beta2=10) norm_image = cv2.normalize(hessian_filter, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) return norm_image
def hessianFilter(): global filterimage imgFilter8 = filters.hessian(img, sigmas=range(1, 10, 2), scale_range=None, scale_step=None, alpha=0.5, beta=0.5, gamma=15, black_ridges=True, mode=None, cval=0) filterimage = imgFilter8 io.imshow(imgFilter8) io.show()
def monolayers(original, logger): logger.info("Finding edges and groups") groups = get_groups(original) logger.info("Finding vignetting") original = downscale_to(original, area_limit=2e5) g = original[:, :, 1] vignetting = find_vignetting(g, groups) vignetting = np.where(groups <= 0, 0, vignetting) g = smooth_with_mask(g - vignetting, mask=groups > 0, sigma=2) logger.info("Finding substrate and monolayer colors") if np.sum(groups == -2) != 0: distance_from_mechanical_vignette = distance_transform_edt( groups != -2) else: distance_from_mechanical_vignette = np.full(groups.shape, np.inf) far_from_mechanical_vignette = distance_from_mechanical_vignette > 50 rng, histogram = get_histogram(g[(groups > 0) & far_from_mechanical_vignette]) peaks, valleys = peaks_and_valleys(histogram, { "distance": 10, "prominence": 1e-3 }) substrate_color = rng[peaks[np.argmax(histogram[peaks])]] best_monolayer_color = (-0.06 + 1) * substrate_color monolayer_peak_index = np.argmin(np.abs(rng[peaks] - best_monolayer_color)) min_monolayer, max_monolayer = rng[valleys[monolayer_peak_index]], rng[ valleys[monolayer_peak_index + 1]] min_monolayer = 2 * rng[peaks[monolayer_peak_index]] - max_monolayer monolayer = (g >= min_monolayer) & (g <= max_monolayer) & ( groups > 0) & far_from_mechanical_vignette monolayer = remove_small_objects(monolayer, np.sum(groups > 0) // 200) monolayer = binary_closing(monolayer, disk(5)) monolayer = binary_dilation(monolayer, disk(1)) monolayer = fill_shape(monolayer) logger.info("Separating overlapping monolayers") distance = distance_transform_edt(monolayer) ridges = hessian(distance, black_ridges=True) * monolayer markers = im_label(ridges == 1) monolayer_group = watershed(-distance, markers, mask=monolayer) monolayer_group = prune(monolayer_group, rel_threshold=0.05) for group in range(1, np.max(monolayer_group) + 1): monolayer_group = fill_shape(monolayer_group, group, tol=2) return {"original": original, "monolayers": monolayer_group}
def filter_show(data): for k in [12, 3088]: img = np.array(data[k]).reshape((28, 28)) image_scharr = scharr(img) image_sobel = sobel(img) image_prewitt = prewitt(img) image_gabor_real, image_gabor_im = gabor(img, frequency=0.65) image_roberts = roberts(img) image_roberts_pos = roberts_pos_diag(img) image_roberts_neg = roberts_neg_diag(img) image_frangi = frangi(img) image_laplace = laplace(img) image_hessian = hessian(img) image_threshold_local_3 = threshold_local(img, 3) image_threshold_local_5 = threshold_local(img, 5) image_threshold_local_7 = threshold_local(img, 7) image_threshold_niblack = threshold_niblack(img, window_size=5, k=0.1) image_threshold_sauvola = threshold_sauvola(img) image_threshold_triangle = img > threshold_triangle(img) fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(8, 8)) ax = axes.ravel() ax[0].imshow(img, cmap=plt.cm.gray) ax[0].set_title('Original image') ax[1].imshow(image_threshold_niblack, cmap=plt.cm.gray) ax[1].set_title('Niblack') ax[2].imshow(image_threshold_sauvola, cmap=plt.cm.gray) ax[2].set_title('Sauvola') ax[3].imshow(image_threshold_triangle, cmap=plt.cm.gray) ax[3].set_title('Triangle') for a in ax: a.axis('off') plt.tight_layout() plt.show() plt.close()
def cellMass(img): """ Calculating of the center of mass coordinate using threshold mask for already detected cell. Treshold function use modifyed Hessian filter. This method optimysed for confocal image of HEK 293 cells with fluorecent- labelled protein who located into the membrane. Results of this method for fluorecent microscop images or fluorecent-labelled proteins with cytoplasmic localization may by unpredictable and incorrect. """ mass_mask = filters.hessian(img, sigmas=range(20, 28, 1)) mass_cntr = msr.center_of_mass(mass_mask) mass_coord = [np.int(mass_cntr[1]), np.int(mass_cntr[0])] logging.info("Image center of mass: %s" % mass_coord) return mass_coord
def hess(image): return hessian(image)
def hessian_filter(filename): img = asarray(Image.open(filename)) img = rgb2gray(img) img = filters.hessian(img, mode="reflect") plt.imsave(filename, img, cmap="gray") return filename
def Hessian(image): image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) return fil.hessian(image)
def test_cropped_camera_image(): image = crop(camera(), ((206, 206), (206, 206))) assert_allclose(frangi(image), np.zeros((100, 100)), atol=1e-03) assert_allclose(frangi(image, black_ridges=True), np.zeros((100, 100)), atol=1e-03) assert_allclose(hessian(image), np.ones((100, 100)), atol=1-1e-07)
#from skimage.data import camera from skimage.filters import frangi, hessian from skimage.io import imread from skimage.color import rgb2gray import matplotlib.pyplot as plt #image = camera() image = rgb2gray(imread("lena.png")) fig, ax = plt.subplots(ncols=3) ax[0].imshow(image, cmap=plt.cm.gray) ax[0].set_title('Original image') ax[1].imshow(frangi(image), cmap=plt.cm.gray) ax[1].set_title('Frangi filter result') ax[2].imshow(hessian(image), cmap=plt.cm.gray) ax[2].set_title('Hybrid Hessian filter result') for a in ax: a.axis('off') plt.tight_layout() plt.show()
def hessian_2d_filter(image): """ TODO """ return filters.hessian(image)
def hessian_filter(img): return filters.hessian(img)
def test_values_decreased(): a = np.multiply(np.ones((3, 3)), 10) assert_equal(frangi(a), np.zeros((3, 3))) assert_equal(hessian(a), np.ones((3, 3)))
def very_abstract(): from skimage.filters import frangi debug = False rand_color = randomcolor.RandomColor() size_x = 10 size_y = 10 upscale_factor = 10 n_labels = 4 sigma = 1 buffer = 0.005 hsv_index = 1 segment_spacing = [100, 10] image_rgb = np.random.uniform(0, 1, (size_x, size_y, 3)) labels = np.random.randint(n_labels + 1, size=( size_x, size_y)) * np.random.randint(0, 2, size=(size_x, size_y)) # segment random image segments = random_walker( image_rgb, labels, multichannel=True, beta=250, copy=False, spacing=segment_spacing, ) all_colors = np.array( rand_color.generate( hue="blue", # luminosity='bright', count=n_labels, format_='Array_rgb')) / 256. for color_index in np.unique(segments): color_hsv = color.rgb2hsv(all_colors[color_index - 1]) # color_hsv[2] = 0.6 + (color_index - 1) * 0.4 / n_labels color_rgb = color.hsv2rgb(color_hsv) image_rgb[segments == color_index] = color_rgb # transform segmented image so it is large, preserving blobs, and blurry image_rgb = rescale(image_rgb, upscale_factor, anti_aliasing=False, multichannel=True) image_rgb = gaussian(image_rgb, sigma=sigma, multichannel=True) image_hsv = color.rgb2hsv(image_rgb) if debug: plt.figure() plt.imshow(image_rgb) plt.show() for pix_frac in [0.9]: total_pixels_switched = int(image_rgb.shape[0] * image_rgb.shape[0] * pix_frac) print(total_pixels_switched) for _ in range(total_pixels_switched): rand_x, rand_y = np.random.choice( image_hsv.shape[0]), np.random.choice(image_hsv.shape[1]) orig_rgb = image_rgb[rand_x, rand_y] rand_value = image_hsv[rand_x, rand_y, hsv_index] x, y = np.where((rand_value * (1 + 0.5 * buffer) >= image_hsv[:, :, hsv_index]) & (rand_value * (1 - 2 * buffer) < image_hsv[:, :, hsv_index])) if len(x) == 0: continue idx = np.random.choice(len(x)) update_rgb = image_rgb[x[idx], y[idx]] image_rgb[x[idx], y[idx]] = orig_rgb image_rgb[rand_x, rand_y] = update_rgb if debug: plt.figure() plt.title(pix_frac) plt.imshow(image_rgb) plt.show() if debug: plt.figure() plt.imshow(image_rgb) plt.show() # filtered_img = prewitt_v(color.rgb2hsv(image_rgb)[:, :, 0]) # filtered_img = meijering(color.rgb2hsv(image_rgb)[:, :, 0]) # filtered_img = sato(color.rgb2hsv(image_rgb)[:, :, 0]) # filtered_details = frangi(color.rgb2hsv(image_rgb)[:, :, 0], # sigmas=range(3, 8, 10), # black_ridges=True, # beta=0.1, # ) filtered_img = frangi( color.rgb2hsv(image_rgb)[:, :, 0], sigmas=range(3, 8, 10), black_ridges=False, # beta=0.1, ) from skimage.filters.rank import median from skimage.morphology import disk, ball filtered_img = median(filtered_img / np.max(filtered_img), disk(10)) filtered_img = filtered_img filtered_img = (filtered_img + np.abs(np.min(filtered_img)) ) / np.max(filtered_img + np.abs(np.min(filtered_img))) filtered_img += 0.8 if debug: plt.figure() plt.imshow(filtered_img, cmap='gray') plt.colorbar() plt.show() num_erosions = 5 eroded_image = hessian(color.rgb2hsv(image_rgb)[:, :, 0]) eroded_aug = np.zeros_like(eroded_image) for n in range(num_erosions): eroded_aug += 1 * eroded_image eroded_image = erosion(eroded_image) if debug: plt.figure() plt.imshow(image_rgb) plt.show() image_hsv = color.rgb2hsv(image_rgb) image_hsv[:, :, 2] *= filtered_img image_hsv[:, :, 2] *= 1 - (0.8 * eroded_aug / np.max(eroded_aug)) image_rgb_shadow_aug = color.hsv2rgb(image_hsv) plt.figure() plt.imshow(image_rgb_shadow_aug) plt.show()
def apply_helper(self, data): return filters.hessian(data, sigmas=self.sigmas)
Frangi filter ============= The Frangi and hybrid Hessian filters can be used to detect continuous edges, such as vessels, wrinkles, and rivers. """ from skimage.data import camera from skimage.filters import frangi, hessian import matplotlib.pyplot as plt image = camera() fig, ax = plt.subplots(ncols=3) ax[0].imshow(image, cmap=plt.cm.gray) ax[0].set_title('Original image') ax[1].imshow(frangi(image), cmap=plt.cm.gray) ax[1].set_title('Frangi filter result') ax[2].imshow(hessian(image), cmap=plt.cm.gray) ax[2].set_title('Hybrid Hessian filter result') for a in ax: a.axis('off') plt.tight_layout() plt.show()
def test_null_matrix(): a = np.zeros((3, 3)) assert_almost_equal(frangi(a), np.zeros((3, 3))) assert_almost_equal(frangi(a, black_ridges=False), np.zeros((3, 3))) assert_equal(hessian(a), np.ones((3, 3)))
# # visualize pickle # with open('../data/DSA_pkl/' + '30131' + '.pickle', 'rb') as handle: # data = pickle.load(handle) # image_dict = data['image_dict'] # for key in image_dict.keys(): # print(key) # image = image_dict[key][:,:,4] # print(image.shape) rescaled_image = rescale(image, 1.5, anti_aliasing=True) print(image.shape, rescaled_image.shape) fig, ax = plt.subplots(ncols=4) ax[0].imshow(image, cmap=plt.cm.gray) ax[0].set_title('Original image') ax[1].imshow(frangi(image), cmap=plt.cm.gray) ax[1].set_title('Frangi filter result') ax[2].imshow(hessian(image, (1, 5), 1), cmap=plt.cm.gray) ax[2].set_title('Hybrid Hessian filter result') ax[3].imshow(rescaled_image[:128, :128], cmap=plt.cm.gray) ax[3].set_title('') for a in ax: a.axis('off') plt.tight_layout() plt.show()
#img_fr = myremoveBoundary( img_fr, mask_inv, dilateSize ) #mysaveImg( img_fr, imagePathSave+'frangi_low' + str(scaleLow) + "_high" + str(scaleHigh) + "_step" + str(scaleStep) + "_beta1" + str(beta1) + '.tif') normFrangi = cv2.convertScaleAbs(img_fr / img_fr.max() * 255) #mysaveImg( normFrangi, 'frangiNorm_low' + str(scaleLow) + "_high" + str(scaleHigh) + "_step" + str(scaleStep) + "_beta1_" + str(beta1) + "_beta2_" + str(beta2) + '.tif') ret, FrangiTH = cv2.threshold(normFrangi, ThFrangi, 255, cv2.THRESH_BINARY) #mysaveImg( FrangiTH, imagePathSave+'frangiTh_low' + str(scaleLow) + "_high" + str(scaleHigh) + "_step" + str(scaleStep) + "_beta1_" + str(beta1) + "_beta2_" + str(beta2) + '.tif') im_BP = myBPfilter(img_mask, BPkersize) #im_BP = myremoveBoundary( im_BP, mask_inv, dilateSize ) ret, BPTH = cv2.threshold(im_BP, ThBP, 255, cv2.THRESH_BINARY) #mysaveImg( BPTH, imagePathSave+'BPTh_ksize' + str(BPkersize) + '_Th' + str(ThBP) +'.tif' ) start_time1 = time.time() img_hs = hessian(img_mask, scale_range=(scaleLow, scaleHigh), scale_step=scaleStep, beta1=beta1) print(time.time() - start_time1) im_BP = numpy.where(im_BP > 0, 1, 0) img_fr = numpy.where(img_fr > 0.6, 1, 0) plt.subplot(1, 3, 1), plt.imshow(img_mask, "gray"), plt.title('img-mask') plt.xticks([]), plt.yticks([]) plt.subplot(1, 3, 2), plt.imshow(img_fr, "gray"), plt.title('frangi') plt.xticks([]), plt.yticks([]) plt.subplot(1, 3, 3), plt.imshow(im_BP, "gray"), plt.title('bandpass') plt.xticks([]), plt.yticks([]) plt.show()
def mountains_series(): def format_axes(fig): for i, ax in enumerate(fig.axes): ax.tick_params(labelbottom=False, labelleft=False, bottom=False, left=False) fig = plt.figure(constrained_layout=False, frameon=False) ax = fig.add_axes([0, 0, 1, 1]) ax.set_facecolor((0.88, 0.87, 0.9)) gs = GridSpec(3, 3, figure=fig, wspace=0, hspace=0.05) axes = [] axes.append(fig.add_subplot(gs[0, :])) axes.append(fig.add_subplot(gs[1, :-1])) axes.append(fig.add_subplot(gs[1:, -1])) axes.append(fig.add_subplot(gs[-1, 0])) axes.append(fig.add_subplot(gs[-1, -2])) # sizes_y = [15, 10, 5, 5, 5] # sizes_x = [5, 5, 10, 5, 5] sizes_y = [20, 12, 5, 5, 5] sizes_x = [5, 5, 10, 5, 5] for i in range(5): debug = False rand_color = randomcolor.RandomColor() size_x = sizes_x[i] size_y = sizes_y[i] upscale_factor = 10 n_labels = 5 sigma = 1 buffer = 0.005 hsv_index = 1 segment_spacing = [10, 10] image_rgb = np.random.uniform(0, 1, (size_x, size_y, 3)) labels = np.random.randint(n_labels + 1, size=( size_x, size_y)) * np.random.randint(0, 2, size=(size_x, size_y)) # segment random image segments = random_walker( image_rgb, labels, multichannel=True, beta=250, copy=False, spacing=segment_spacing, ) all_colors = np.array( rand_color.generate( hue="purple", # luminosity='bright', count=n_labels, format_='Array_rgb')) / 256. for color_index in np.unique(segments): color_hsv = color.rgb2hsv(all_colors[color_index - 1]) # color_hsv[2] = 0.6 + (color_index - 1) * 0.4 / n_labels color_rgb = color.hsv2rgb(color_hsv) image_rgb[segments == color_index] = color_rgb # transform segmented image so it is large, preserving blobs, and blurry image_rgb = rescale(image_rgb, upscale_factor, anti_aliasing=False, multichannel=True) image_rgb = gaussian(image_rgb, sigma=sigma, multichannel=True) image_hsv = color.rgb2hsv(image_rgb) if debug: plt.figure() plt.imshow(image_rgb) plt.show() for pix_frac in [0.9]: total_pixels_switched = int(image_rgb.shape[0] * image_rgb.shape[0] * pix_frac) print(total_pixels_switched) for _ in range(total_pixels_switched): rand_x, rand_y = np.random.choice( image_hsv.shape[0]), np.random.choice(image_hsv.shape[1]) orig_rgb = image_rgb[rand_x, rand_y] rand_value = image_hsv[rand_x, rand_y, hsv_index] x, y = np.where( (rand_value * (1 + 0.5 * buffer) >= image_hsv[:, :, hsv_index]) & (rand_value * (1 - 2 * buffer) < image_hsv[:, :, hsv_index])) if len(x) == 0: continue idx = np.random.choice(len(x)) update_rgb = image_rgb[x[idx], y[idx]] image_rgb[x[idx], y[idx]] = orig_rgb image_rgb[rand_x, rand_y] = update_rgb if debug: plt.figure() plt.title(pix_frac) plt.imshow(image_rgb) plt.show() if debug: plt.figure() plt.imshow(image_rgb) plt.show() # filtered_img = prewitt_v(color.rgb2hsv(image_rgb)[:, :, 0]) # filtered_img = meijering(color.rgb2hsv(image_rgb)[:, :, 0]) # filtered_img = sato(color.rgb2hsv(image_rgb)[:, :, 0]) # filtered_details = frangi(color.rgb2hsv(image_rgb)[:, :, 0], # sigmas=range(3, 8, 10), # black_ridges=True, # beta=0.1, # ) filtered_img = frangi( color.rgb2hsv(image_rgb)[:, :, 0], sigmas=range(3, 8, 10), black_ridges=True, # beta=0.1, ) from skimage.filters.rank import median from skimage.morphology import disk, ball filtered_img = median(filtered_img / np.max(filtered_img), disk(10)) filtered_img = filtered_img filtered_img = 1.5 * (filtered_img + np.abs( np.min(filtered_img))) / np.max(filtered_img + np.abs(np.min(filtered_img))) filtered_img += 0.6 if debug: plt.figure() plt.imshow(filtered_img, cmap='gray') plt.colorbar() plt.show() num_erosions = 5 eroded_image = hessian(color.rgb2hsv(image_rgb)[:, :, 0]) eroded_aug = np.zeros_like(eroded_image) for n in range(num_erosions): eroded_aug += 1 * eroded_image eroded_image = erosion(eroded_image) if debug: plt.figure() plt.imshow(image_rgb) plt.show() image_hsv = color.rgb2hsv(image_rgb) image_hsv[:, :, 2] *= filtered_img image_hsv[:, :, 2] *= 1 - (0.8 * eroded_aug / np.max(eroded_aug)) image_rgb_shadow_aug = color.hsv2rgb(image_hsv) # plt.figure() # plt.imshow(image_rgb_shadow_aug) # plt.show() axes[i].imshow(image_rgb_shadow_aug) format_axes(fig) gs.tight_layout(fig, pad=1.2, h_pad=0.5) plt.show()
def test_energy_decrease(): a = np.zeros((5, 5)) a[2, 2] = 1. assert frangi(a).std() < a.std() assert frangi(a, black_ridges=False).std() < a.std() assert hessian(a).std() > a.std()