def get_watershed(image, save_labels=False, plot=False): """ uses watershed transformation to get clusters from the presented U-matrix of the SOM :param image: u_matrix representation of the SOM loaded from pickle :param save_labels: bool to save the label matrix :param plot: bool to plot diagrams showing the found clusters :return: matrix of labels each corresponding to a cluster """ filters.try_all_threshold(image) binary = image < filters.threshold_otsu(image) distance = ndi.distance_transform_edt(binary) local_maxi = peak_local_max(distance, indices=False, labels=binary, footprint=np.ones((1, 1))) markers = ndi.label(local_maxi)[0] final_labels = watershed(distance, markers, mask=binary) img, ax = plt.subplots(1, 1) ax.imshow(final_labels) plt.show(img) if save_labels: with open('watershed_cluster.pickle', 'wb') as handle: pickle.dump(final_labels, handle, protocol=pickle.HIGHEST_PROTOCOL) if plot: fig, axes = plt.subplots(ncols=3, figsize=(9, 3), sharex='all', sharey='all') ax = axes.ravel() ax[0].imshow(image, cmap='gray', interpolation='nearest') ax[0].set_title('U-Matrix') ax[1].imshow(-distance, cmap='gray', interpolation='nearest') ax[1].set_title('Distances') ax[2].imshow(final_labels, cmap=plt.cm.get_cmap('gnuplot', len(np.unique(final_labels)))) ax[2].set_title('Watershed clusters') for a in ax: a.set_axis_off() fig.tight_layout() plt.show() return final_labels
def simple_binarization_example(filepath): orig = io.imread(filepath) orig = color.rgb2gray(orig) fig, ax = try_all_threshold(orig, figsize=(10, 8), verbose=False) plt.show()
def threshold(file='zones/0.png', t='otsu', img=None): from skimage.filters import try_all_threshold from skimage.filters import threshold_mean, threshold_li, threshold_otsu if img is None: img = misc.imread(file) fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False) plt.show() thresh = None if t == 'otsu': thresh = threshold_otsu(img) elif t == 'mean': thresh = threshold_mean(img) else: thresh = threshold_li(img) binary = img > thresh fig, axes = plt.subplots(ncols=2, figsize=(8, 3)) ax = axes.ravel() ax[0].imshow(img, cmap=plt.cm.gray) ax[0].set_title('Original image') ax[1].imshow(binary, cmap=plt.cm.gray) ax[1].set_title('Result') for a in ax: a.axis('off') plt.show() return binary
def get_all_threshold_images(self): # All binary image set fig_all, ax_all = filters.try_all_threshold(self.img, figsize=(10, 8), verbose=False) plt.savefig('imgs/all_binary_images.png') print('all_binary_images.png saved in imgs folder')
def threshold_puncta(img, data, input_params, channel): #z_size = img.shape[0] float_img = img_as_float(img) #print(float_img) # THRESHOLD TEST #z = int(float_img.shape[0]/2) fig, ax = filters.try_all_threshold(float_img[:, :], figsize=(10, 8), verbose=False) plt.savefig(os.path.join(input_params.output_path, data.rep_name + " " + channel + 'thresh_test.png'), dpi=300) plt.close() threshold = filters.threshold_yen(float_img) mask = float_img >= threshold #for z in range(z_size): mask[:, :] = nd.morphology.binary_fill_holes(mask[:, :]) mask = nd.morphology.binary_opening(mask) ### WATERSHED TEST labels, _ = nd.label(mask) #distance = nd.distance_transform_edt(mask) ##custom faster solution for getting markers #sure_fg = distance #sure_fg[sure_fg <= 0.4*distance.max()] = 0 #sure_fg = sure_fg > 0 #sure_fg = nd.morphology.binary_erosion(sure_fg) markers, num_regions = nd.label(mask) print(num_regions) #row, col = optimum_subplots(mask.shape[0]) #fig, ax = plt.subplots(row, col) #img = img.astype(np.uint16) # not sure if this is allowed #ax = ax.flatten() #for idx, a in enumerate(ax): #if idx < mask.shape[0]: #labeled_image = label2rgb(markers[idx, :, :], image=exposure.equalize_adapthist(img[idx, :, :]), #alpha=0.3, bg_label=0, bg_color=[0, 0, 0]) #a.imshow(labeled_image) #clear_axis_ticks(a) #plt.savefig(os.path.join(input_params.output_path, data.rep_name +" "+channel+ 'watershed_test.png'), dpi=300) #plt.close() return num_regions
def topology_map(image_grid, upscale, smooth): no_lines = len(image_grid) no_columns = len(image_grid[0]) moves = [(-1, 0), (0, 1), (1, 0), (0, -1)] u_matrix = np.zeros((2 * no_lines - 1, 2 * no_columns - 1), dtype=np.float16) print('Minimum image grid weight', np.min(image_grid)) print('Maximum image grid weight', np.max(image_grid)) for line in range(no_lines): for column in range(no_columns): for move in moves: new_line = line + move[0] new_column = column + move[1] if new_line < 0 or new_column < 0: continue if new_line >= no_lines or new_column >= no_columns: continue u_mat_line = 2 * line + move[0] u_mat_column = 2 * column + move[1] u_matrix[u_mat_line][u_mat_column] = \ np.linalg.norm(image_grid[line][column] - image_grid[new_line][new_column]) u_matrix = normalize(u_matrix) print(u_matrix) topology_map = smooth_u(u_matrix) fig, ax = filters.try_all_threshold(topology_map) plt.savefig(curr_folder / vis_type / 'thresholding.png') plt.clf() topology_landscape(topology_map, 'landscape') # topology_map = upscale_map(topology_map, upscale) # topology_map = np.round(gaussian(topology_map, sigma = smooth), 2) io.imsave(curr_folder / vis_type / 'u_matrix.png', u_matrix) io.imsave(curr_folder / vis_type / 'topology_map.png', topology_map) return u_matrix
from skimage.filters import try_all_threshold path = E:\DeepLearning os.chdir('E:\DeepLearning') #from skimage import data img = cv2.imread('binary_img.jpg') #grayscale = rgb2gray(img) input_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ##skimage.filters.thresholding.threshold_isodata ##skimage.filters.thresholding.threshold_li ##skimage.filters.thresholding.threshold_mean ##skimage.filters.thresholding.threshold_minimum ##skimage.filters.thresholding.threshold_otsu ##skimage.filters.thresholding.threshold_triangle ##skimage.filters.thresholding.threshold_yen #we are getting all this filters using the try_all_threshold #spliting the data into fig and ax fig, axis = try_all_threshold(input_img) plt.show() #save the image into directory. cv2.imwrite(path+"all_figure_.jpg",fig)
def thresholdComparison(img): fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False) plt.show()
def try_thresholds(image): fig, ax = try_all_threshold(image, figsize=(10, 8), verbose=False) plt.show()
def show_thresholds(self): wsf = self.images[self.image_i].get_frame() filters.try_all_threshold(wsf.image_raw(), figsize=(10, 8), verbose=True) plt.show()
# Find the mean threshold value mean_val = threshold_mean(image) # Threshold the image binary_image = image > mean_val # Plot the thresholded image fig = plt.figure(figsize=(3, 3)) plt.imshow(binary_image, cmap="gray") plt.title("Mean Threshold: " + str(mean_val)) plt.show() # %% fig, ax = try_all_threshold(image, figsize=(10, 10), verbose=False) plt.show() # %% # Apply Minimum thresholding min_val = threshold_minimum(bw_image) binary_image_min = bw_image > min_val # Apply Otsu thresholding otsu_val = threshold_otsu(bw_image) binary_image_otsu = bw_image > otsu_val # Display the thresholded images fig = plt.figure(figsize=(12, 12))
import skimage.color as color from skimage import io image = io.imread('Data/TL_41_10_129161_15.jpg', cmap='grey') images = io.ImageCollection('Data/*.jpg') plt.imshow(image) plt.show() image_thr = image > 180 plt.imshow(image_thr) plt.show() # image_threshold = filters.threshold_local(image, block_size=93, offset=16) image_threshold = filters.threshold_local(image, block_size=51, offset=10) image_seg = image > image_threshold plt.imshow(image_seg) plt.show() image_threshold2 = filters.threshold_otsu(image, nbins=256) image_seg2 = image > image_threshold2 plt.imshow(image_seg2) plt.show() fig = filters.try_all_threshold(image, figsize=(8, 5)) # plt.imshow(fig) plt.show() # images = io.ImageCollection('Data/*.jpg') # print('Type:', type(images)) # images.files
border_polygon = convert_wkt_to_polygon(config.BORDER_POLYGON_TEXANA) # border_polygon = convert_wkt_to_polygon(config.BORDER_POLYGON) count = 0 size = 3 for folder in os.listdir(input_dir): if folder.endswith('.data'): for file in os.listdir(input_dir + folder): if file.endswith('.img'): p = rasterio.open(input_dir + folder + "\\" + file) print(folder + "\\" + file) [border_arr], border_xy = mask.mask(dataset=p, shapes=[border_polygon], all_touched=True, crop=True) fig, axes = plt.subplots(nrows=2, figsize=(7, 8)) ax0, ax1 = axes plt.gray() border_arr = normalize(border_arr) ax0.imshow(border_arr) ax0.set_title(f'Original ({file})') kernel = np.ones((size, size)).astype("uint8") g_img = opening(border_arr, kernel) ax1.imshow(g_img) ax1.set_title(f'After morpohological opening ({size}x{size})') fig_temp, ax = try_all_threshold(g_img, verbose=False) plt.tight_layout() plt.show() count += 1 input() if count == 5: exit()
def try_all_threshold_filter(img): new_img = filters.try_all_threshold(img, figsize=(10, 6), verbose=True) plt.show()
import numpy as np import pandas as pd import matplotlib.pyplot as plt from skimage import io from skimage import data from skimage.filters import threshold_otsu, threshold_local, try_all_threshold from matplotlib.backends.backend_pdf import PdfPages image = io.imread('imageimage.jpeg') fig, ax = try_all_threshold(image, figsize=(7, 8)) #plt.teste = try_all_threshold(image, figsize=(7, 8)) #plt.savefig(pp, format='pdf') #fig.savefig('test.png') #io.imsave('output.png', newimage) #newimage.plt.savefig('foo.png') #newimage.plt.savefig('foo.pdf') #plt.savefig('foo.png') #fig = plt.figure(newimage) #test for the image
def try_thresholdings(img): """ try all thresholding """ fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False) plt.show()
import matplotlib.pyplot as plt os.chdir('/home/sambeet/data/kaggle/carvana/') image_list = os.listdir('train_resized/') x = misc.imread('train_resized/' + image_list[0],flatten = True) hist = np.histogram(x, bins=np.arange(0, 256)) plt.plot(hist[1][:-1], hist[0], lw=2) z = filters.scharr((x/255.)) #z = filters.gaussian(z,1.) z = canny(z,1) z = ndi.binary_closing(z,structure=np.ones((3,3))) z = ndi.binary_fill_holes(z,np.ones((3,3))) io.imshow(z) z = filters.prewitt((x-127.5)/255.) z = filters.scharr((x-127.5)/255.) x = abs(x - 127.5)/127.5 threshold_li = filters.threshold_yen((x)) threshold_li = filters.threshold_otsu(x) threshold_li = filters.threshold_isodata(x) z = x > threshold_li io.imshow(z) x = misc.imread('train/' + image_list[0],flatten = True) x = abs(x - 127.5)/127.5 #x_rgb = misc.imread('train/' + image_list[0]) threshold_li = filters.try_all_threshold(z1) z = x > threshold_li io.imshow((z -.5)) z1 = filters.rank.autolevel((x-127.5)/127.5,disk(20))
def threshold_test(data, input_params): img = data.nuc_img z_size = img.shape[0] med_img = np.zeros(shape=img.shape) for z in range(z_size): temp_img = img[z, :, :] med_img[z, :, :] = cv2.medianBlur(temp_img, ksize=5) med_img = img_as_float(med_img) ## THRESHOLD TEST z = int(med_img.shape[0] / 2) fig, ax = filters.try_all_threshold(med_img[z, :, :], figsize=(10, 8), verbose=False) # plt.show() plt.savefig(os.path.join(input_params.output_path, data.rep_name + 'thresh_test.png'), dpi=300) plt.close() # threshold = filters.threshold_otsu(med_img) threshold = filters.threshold_triangle(med_img) nuc_mask = med_img >= threshold for z in range(z_size): nuc_mask[z, :, :] = nd.morphology.binary_fill_holes(nuc_mask[z, :, :]) nuc_mask = nd.morphology.binary_opening(nuc_mask) ### WATERSHED TEST labels, _ = nd.label(nuc_mask) distance = nd.distance_transform_edt(nuc_mask) ##custom faster solution for getting markers sure_fg = distance sure_fg[sure_fg <= 0.4 * distance.max()] = 0 sure_fg = sure_fg > 0 sure_fg = nd.morphology.binary_erosion(sure_fg) markers, num_regions = nd.label(sure_fg) row, col = optimum_subplots(nuc_mask.shape[0]) fig, ax = plt.subplots(row, col) ax = ax.flatten() for idx, a in enumerate(ax): if idx < nuc_mask.shape[0]: labeled_image = label2rgb(markers[idx, :, :], image=exposure.equalize_adapthist( data.nuc_img[idx, :, :]), alpha=0.3, bg_label=0, bg_color=[0, 0, 0]) a.imshow(labeled_image) clear_axis_ticks(a) plt.savefig(os.path.join(input_params.output_path, data.rep_name + 'watershed_test.png'), dpi=300) plt.close()
dist=np.array([ [0,0], [max_width-1,0], [max_width-1,max_height-1], [0,max_height-1] ],dtype="float32") M=cv2.getPerspectiveTransform(peck,dist) warped=cv2.warpPerspective(image,M,(max_width,max_height)) return warped warped=four_point_transform(orig,scr.reshape(4,2)*ratio) warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) T = threshold_local(warped, 11, offset = 10, method = "gaussian") arped = (warped > T).astype("uint8") * 255 marped=try_all_threshold(warped, figsize=(10, 6), verbose=True) marped=imutils.resize(warped,width=650) arped=imutils.resize(arped,width=650) cv2.imshow("Orig",marped) cv2.imshow("Image",arped) cv2.waitKey(0)
"""Trying other methods (Thresholding) As we saw in the video, not being sure about what thresholding method to use isn't a problem. In fact, scikit-image provides us with a function to check multiple methods and see for ourselves what the best option is. It returns a figure comparing the outputs of different global thresholding methods. You will apply this function to this image, matplotlib.pyplot has been loaded as plt. Remember that you can use try_all_threshold() to try multiple global algorithms. > Import the try all function. > Import the rgb to gray convertor function. > Turn the fruits image to grayscale. > Use the try all method on the grayscale image. """ import sys from skimage.filters import try_all_threshold from skimage.color import rgb2gray from matplotlib import pyplot as plt sys.path.append('./helpers') from settings import nda_import_image, show_image str_fruit_image_path = './dataset/chapter 1/fruits-2.jpg' img_fruit = nda_import_image(str_fruit_image_path) img_fruit_grayscale = rgb2gray(img_fruit) fig, ax = try_all_threshold(img_fruit_grayscale, verbose=False) plt.show()
from skimage.filters import try_all_threshold from skimage.io import imread from skimage.color import rgb2gray from skimage.filters import threshold_otsu import matplotlib.pyplot as plt vehicle_image = imread('image1.jpg') gray_image = rgb2gray(vehicle_image) # skimage change into gray using 0 to 1 scale # so for convinence we extend range back to 0 to 255 gray_car_image = gray_image * 255 fig, ax = try_all_threshold(gray_car_image, figsize=(10, 8), verbose=False) plt.show()
def test_thresh(img): gauss = filters.gaussian(img, sigma=2) equalize = exposure.equalize_adapthist(gauss) fig, ax = filters.try_all_threshold(equalize)
#Global thresholding algorithms # Applied when image is highly contrasted with a uniform background from skimage.filters import try_all_threshold from skimage import data, io image = data.page() thresh = try_all_threshold(image) io.show()
show_image(binary_local, 'Local thresholding') -------------------------------------------------- # Exercise_6 # Import the try all function from skimage.filters import try_all_threshold # Import the rgb to gray convertor function from skimage.color import rgb2gray # Turn the fruits image to grayscale grayscale = rgb2gray(fruits_image) # Use the try all method on the grayscale image fig, ax = try_all_threshold(grayscale, verbose=False) # Show the resulting plots plt.show() -------------------------------------------------- # Exercise_7 # Import threshold and gray convertor functions from skimage.filters import threshold_otsu from skimage.color import rgb2gray # Turn the image grayscale gray_tools_image = rgb2gray(tools_image) # Obtain the optimal thresh thresh = threshold_otsu(gray_tools_image)
gray_image = rgb2grey(test_image) # Combine masks mask = np.zeros(gray_image.shape[:2], np.uint16) for mask_idx in range(test_masks.shape[0]): mask[test_masks[mask_idx] > 0] = mask_idx + 1 # Plot plt.imshow(gray_image, 'gray') plt.show() plt.imshow(mask) plt.colorbar() plt.show() # Try thresholding methods for getting mask fig, ax = try_all_threshold(gray_image, figsize=(12, 10), verbose=False) plt.show() from skimage import measure from skimage.filters import median from skimage.filters import threshold_otsu from skimage.filters import threshold_mean from skimage.morphology import disk # Threshold threshold_function = threshold_otsu #threshold_function = threshold_mean thresh = threshold_function(gray_image) threshold_mask = gray_image > thresh # Smoothing
# - [scikit-image](http://scikit-image.org/docs/dev/auto_examples/xx_applications/plot_thresholding.html) # # There are many methods and they can be complicated to implement yourself. Both Fiji and scikit-image offers many of them as built in functions so you can automatically try all of them on your image # # In[5]: from skimage.io import imread import matplotlib.pyplot as plt import numpy as np bone_img = imread("ext-figures/bonegfiltslice.png") / 255.0 from skimage.filters import try_all_threshold fig, ax = try_all_threshold(bone_img, figsize=(10, 8), verbose=True) # # Pitfalls # # While an incredibly useful tool, there are many potential pitfalls to these automated techniques. # # ### Histogram-based # # These methods are very sensitive to the distribution of pixels in your image and may work really well on images with equal amounts of each phase but work horribly on images which have very high amounts of one phase compared to the others # # ### Image-based # # These methods are sensitive to noise and a large noise content in the image can change statistics like entropy significantly. # # ### Results-based #
def try_all_threshold_filter(image): new_img = filters.try_all_threshold(image, figsize=(15,30 ), verbose=True) plt.show()
image = imread("./counting/data/raw/001cell.png") image = rgb2gray(image) plt.imshow(image, cmap="gray") #%% noise removal (median filter is an edge preserver (performs better than Gaussian)) med = median(image, disk(5)) plt.imshow(med, cmap="gray") #%% remove background background = white_tophat(med, disk(5)) plt.imshow(background, cmap="gray") #%% can threshold only gray images fig, ax = try_all_threshold(background, verbose=False) plt.show() #%% threasholding li_thresh = threshold_li(background) binary_li = background > li_thresh #invert image (make the cells white and background black): bad for labelling #inverted = np.invert(binary_li) plt.imshow(binary_li, cmap="gray") #%% post-process thresholding opening = binary_opening(binary_li) plt.imshow(opening, cmap="gray")
ax[0].axis('off') ax[1].hist(image.ravel(), bins=256) ax[1].set_title('Histogram') ax[1].axvline(thresh, color='r') ax[2].imshow(binary, cmap=plt.cm.gray) ax[2].set_title('Thresholded') ax[2].axis('off') plt.show() ###################################################################### # If you are not familiar with the details of the different algorithms and the # underlying assumptions, it is often difficult to know which algorithm will give # the best results. Therefore, Scikit-image includes a function to evaluate # thresholding algorithms provided by the library. At a glance, you can select # the best algorithm for you data without a deep understanding of their # mechanisms. # from skimage.filters import try_all_threshold img = data.page() # Here, we specify a radius for local thresholding algorithms. # If it is not specified, only global algorithms are called. fig, ax = try_all_threshold(img, radius=20, figsize=(10, 8), verbose=False) plt.show()
ax[0].set_title('Original') ax[0].axis('off') ax[1].hist(image.ravel(), bins=256) ax[1].set_title('Histogram') ax[1].axvline(thresh, color='r') ax[2].imshow(binary, cmap=plt.cm.gray) ax[2].set_title('Thresholded') ax[2].axis('off') plt.show() ###################################################################### # If you are not familiar with the details of the different algorithms and the # underlying assumptions, it is often difficult to know which algorithm will give # the best results. Therefore, Scikit-image includes a function to evaluate # thresholding algorithms provided by the library. At a glance, you can select # the best algorithm for you data without a deep understanding of their # mechanisms. # from skimage.filters import try_all_threshold img = data.page() # Here, we specify a radius for local thresholding algorithms. # If it is not specified, only global algorithms are called. fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False) plt.show()
def try_all_thresholding(img_file): img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE) fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False) plt.show()