def Image_ws_tranche(image): laser = Detect_laser(image) laser_tranche = tranche_image(laser,60) image_g = skimage.color.rgb2gray(image) image_g = image_g * laser_tranche image_med = rank2.median((image_g*255).astype('uint8'),disk(8)) image_clahe = exposure.equalize_adapthist(image_med, clip_limit=0.03) image_clahe_stretch = exposure.rescale_intensity(image_clahe, out_range=(0, 256)) image_grad = rank2.gradient(image_clahe_stretch,disk(3)) image_grad_mark = image_grad<20 image_grad_forws = rank2.gradient(image_clahe_stretch,disk(1)) image_grad_mark_closed = closing(image_grad_mark,disk(1)) Labelised = (skimage.measure.label(image_grad_mark_closed,8,0))+1 Watersheded = watershed(image_grad_forws,Labelised) cooc = coocurence_liste(Watersheded,laser,3) x,y = compte_occurences(cooc) return x,y
def segm(img): den = rank.median(img, morph.disk(3)) # continuous regions (low gradient) markers = rank.gradient(den, morph.disk(5)) < 10 mrk, tot = ndimage.label(markers) grad = rank.gradient(den, morph.disk(2)) labels = morph.watershed(grad, mrk) return seg_regions(img, labels, tot)
def segment(img, outimg): img = np.array(Image.open(img)) den = rank.median(img, morph.disk(3)) # continuous regions (low gradient) markers = rank.gradient(den, morph.disk(5)) < 10 mrk, tot = ndimage.label(markers) grad = rank.gradient(den, morph.disk(2)) labels = morph.watershed(grad, mrk) print 'Total regions:', tot regs = big_regions(labels, tot) spr = 3 spc = 6 plot_seg(spr, spc, 1, img, cm.gray, 1, 'image') plot_seg(spr, spc, 2, den, cm.gray, 1, 'denoised') plot_seg(spr, spc, 3, grad, cm.spectral, 1, 'gradient') plot_seg(spr, spc, 4, mrk, cm.spectral, 1, 'markers') plot_seg(spr, spc, 5, labels, cm.spectral, 1, 'regions\n%i' % tot) plot_seg(spr, spc, 6, img, cm.gray, 1, 'composite') plot_seg(spr, spc, 6, labels, cm.spectral, 0.7, 'composite') plot_mask(spr, spc, 7, 0, labels, regs, cm.spectral, 'main region') plot_mask(spr, spc, 8, 1, labels, regs, cm.spectral, '2nd region') plot_mask(spr, spc, 9, 2, labels, regs, cm.spectral, '3rd region') plot_mask(spr, spc, 10, 3, labels, regs, cm.spectral, '4th region') plot_mask(spr, spc, 11, 4, labels, regs, cm.spectral, '5th region') plot_mask(spr, spc, 12, 5, labels, regs, cm.spectral, '6th region') plot_crop(spr, spc, 13, 0, img, labels, regs, cm.gray) plot_crop(spr, spc, 14, 1, img, labels, regs, cm.gray) plot_crop(spr, spc, 15, 2, img, labels, regs, cm.gray) plot_crop(spr, spc, 16, 3, img, labels, regs, cm.gray) plot_crop(spr, spc, 17, 4, img, labels, regs, cm.gray) plot_crop(spr, spc, 18, 5, img, labels, regs, cm.gray) #plt.savefig('test.eps', dpi=300) plt.savefig(outimg, dpi=300)
mypic_rev_small = mypic_rev[:200, :] mypic_rev = mypic_rev_small mypic_rev_log = np.log10(mypic_rev + 0.001) mypic_rev_gauss = sp.ndimage.gaussian_filter(mypic_rev, sigma=3) mypic_rev_log_gauss = sp.ndimage.gaussian_filter(mypic_rev_log, sigma=3) mypic_rev_gauss_bin = mypic_rev_gauss > np.percentile( mypic_rev_gauss, p) mypic_rev_log_gauss_bin = mypic_rev_log_gauss > np.percentile( mypic_rev_log_gauss, p) mypic_rev_gauss_bin_close = sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_gauss_bin)) mypic_rev_log_gauss_bin_close = sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_log_gauss_bin)) mypic_rev_gauss_grad = rank.gradient(pic_to_ubyte(mypic_rev_gauss), disk(3)) mypic_rev_log_gauss_grad = rank.gradient( pic_to_ubyte(mypic_rev_log_gauss), disk(3)) mypic_rev_gauss_grad_bin = mypic_rev_gauss_grad > np.percentile( mypic_rev_gauss_grad, p) mypic_rev_log_gauss_grad_bin = mypic_rev_log_gauss_grad > np.percentile( mypic_rev_log_gauss_grad, p) mypic_rev_gauss_grad_bin_close = sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_gauss_grad_bin)) mypic_rev_log_gauss_grad_bin_close = sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_log_gauss_grad_bin)) bfh = sp.ndimage.binary_fill_holes(mypic_rev_gauss_grad_bin_close) bfh_rm = remove_small_objects(bfh, MIN_SEGMENT_SIZE) log_bfh = sp.ndimage.binary_fill_holes( mypic_rev_log_gauss_grad_bin_close) log_bfh_rm = remove_small_objects(log_bfh, MIN_SEGMENT_SIZE)
from scipy import ndimage import matplotlib.pyplot as plt from skimage.morphology import watershed, disk from skimage import data from skimage.filter 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) --> markers markers = rank.gradient(denoised, disk(5)) < 10 markers = ndimage.label(markers)[0] #local gradient gradient = rank.gradient(denoised, disk(2)) # process the watershed labels = watershed(gradient, markers) # display results fig, axes = plt.subplots(ncols=4, figsize=(8, 2.7)) fig,suptitle('George - Sementation (scikit-image)') ax0, ax1, ax2, ax3 = axes ax0.imshow(image, cmap=plt.cm.gray, interpolation='nearest') ax1.imshow(gradient, cmap=plt.cm.spectral, interpolation='nearest')
#################################### Gradient Image red_chan = gray_image io.imshow(red_chan) close = closing(red_chan, octagon(4,4)) io.imshow(close) opening = opening(close, octagon(6,6)) io.imshow(opening) rec = reconstruction(opening, close) rec = exposure.rescale_intensity(rec, out_range=(0,1)) gradient = gradient(rec, disk(5)) ######################################################## Apply watershed to gradient using imposed markers ### This is where I am having trouble. I have the gradient image and the internal marker location. I want ### to create a marker image with the internal marker (located at the center of the optic disk) and ### the external marker drawn as a circle around the optic disk so that the watershed algorithm can ### evaluate the specific contour of the disk when feeding in the gradient image and the marker image. ### What I need to know is how to create that marker image. ### The radius of the circle (external marker) with center as the internal marker can be anything as long as it is ### larger than the optic disk, completely covering it. circle = circle_perimeter(local_maxi[0,0], local_maxi[0,1], 35) #circle = ndimage.label(circle)[0] #markers = np.zeros_like(rec) #markers[local_maxi[0,0], local_maxi[0,1]] = 1 #markers[circle] = 1
imshow(filter_relativ_height_sidewalk, cmap=plt.cm.gray) ; plt.show(); Z_around_sidewalk = Z * filter_relativ_height_sidewalk ; imshow(Z_around_sidewalk, cmap=plt.cm.gray) ; #Z_around_sidewalk[Z_around_sidewalk!=0] #new_viewer = viewer.ImageViewer(Z_around_sidewalk) ; new_viewer.show() ; tmp_min = np.min(Z_around_sidewalk[isnan(Z_around_sidewalk)==False]) ; tmp_max = np.max(Z_around_sidewalk[isnan(Z_around_sidewalk)==False]) ; Z_around_sidewalk= (Z_around_sidewalk - (tmp_max+tmp_min)/2 ) / (tmp_max-tmp_min) ; convert_to_float = img_as_float(filter_relativ_height_sidewalk) convert_to_float[isnan(convert_to_float)==False] convert_to_int = img_as_int(Z_around_sidewalk) ; viewer.ImageViewer(convert_to_int).show() ; grad = gradient(convert_to_int,disk(1)) ; sobel_result = sobel(convert_to_int,sidewalk_mask) viewer.ImageViewer(sobel_result).show() new_viewer = viewer.ImageViewer(grad) new_viewer += lineprofile.LineProfile() new_viewer.show() imshow(grad, cmap=plt.cm.gray); plt.show(); from skimage.morphology import disk from skimage.filter.rank import gradient
`skimage.dilate` and `skimage.erode` are equivalent filters (see below for comparison). Here is an example of the classical morphological greylevel filters: opening, closing and morphological gradient. """ from skimage.filter.rank import maximum, minimum, gradient ima = data.camera() closing = maximum(minimum(ima, disk(5)), disk(5)) opening = minimum(maximum(ima, disk(5)), disk(5)) grad = gradient(ima, disk(5)) # display results fig = plt.figure(figsize=[10, 7]) plt.subplot(2, 2, 1) plt.imshow(ima, cmap=plt.cm.gray) plt.xlabel('original') plt.subplot(2, 2, 2) plt.imshow(closing, cmap=plt.cm.gray) plt.xlabel('greylevel closing') plt.subplot(2, 2, 3) plt.imshow(opening, cmap=plt.cm.gray) plt.xlabel('greylevel opening') plt.subplot(2, 2, 4) plt.imshow(grad, cmap=plt.cm.gray) plt.xlabel('morphological gradient')
def gredientSeg(preprocessedImage1, raw_image, minAreaSize, maxAreaSize, thre): """ :param preprocessedImage: a greyscale image :param raw_image: a raw image for highlighting segmented cells :param minAreaSize: the minimum area size of the cell :param maxAreaSize: maximum area size of the cell :return: """ preprocessedImage, denoised, gradientIm, thresh, imgDisplay, contours = [], [], [], [], [], [] imgDisplay = raw_image preprocessedImage = preprocessedImage1.astype(np.uint8) if len(preprocessedImage.shape) > 2: preprocessedImage = cv2.cvtColor(preprocessedImage, cv2.COLOR_BGR2GRAY) preprocessedImage = img_as_ubyte(preprocessedImage) # denoise image denoised = rank.median(preprocessedImage, disk(2)) # local ingredient gradientIm = rank.gradient(denoised, disk(thre)) thresh = cv2.threshold(gradientIm, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # fused the the mask and the original image for extracting morph features thresh = cv2.bitwise_and(thresh, preprocessedImage) # find contours in the the mask _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) color = np.random.randint(0, 255, (len(contours), 3)) mask_colored = np.zeros_like(raw_image, ) pts, rectang, cellFeatures = [], [], [] for (ii, cnt) in enumerate(contours): ((x, y), radius) = cv2.minEnclosingCircle(cnt) tmp_perim = cv2.arcLength(cnt, True) tmp_approx = cv2.approxPolyDP(cnt, 0.04 * tmp_perim, True) (x, y, tmp_w, tmp_h) = cv2.boundingRect(tmp_approx) ar = tmp_w / float(tmp_h) # if ar >= 0.95 and ar <= 1.05: # "sss" # else: # del cnt # continue area = cv2.contourArea(cnt) rect = cv2.boundingRect(cnt) (x1, y1, w1, h1) = rect cntIndex, mergedCnt = mergeOverSegmentedContours(contours, cnt) if mergedCnt is not None: cnt = [] cnt = mergedCnt del contours[cntIndex] if area < minAreaSize or area > maxAreaSize or hierarchy[0, ii, 3] != -1: # del contours[ii] continue else: cellMorph = getCellIntensityModule(cnt, imgDisplay) cellFeatures.append(cellMorph) cv2.drawContours( mask_colored, [cnt], -1, color[ii].tolist(), thickness=cv2.FILLED, ) cv2.drawContours(imgDisplay, [cnt], -1, (0, 255, 0), 1) rectang.append((x1, y1, w1, h1)) pts.append([x, y]) del thresh, raw_image, preprocessedImage, preprocessedImage1, denoised, gradientIm return pts, rectang, mask_colored, imgDisplay, cellFeatures
from skimage import io from skimage.morphology import watershed, disk from skimage import data from skimage.filter import rank import cv2 image = io.imread('cerebro.jpg') # makes the image grey colormap gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # denoise image denoised = rank.median(gray, disk(1)) # create the sheds markers = rank.gradient(denoised, disk(1)) < 15 markers = ndi.label(markers)[0] # process the watershed labels = watershed(gray, markers) # display results fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8), sharex=True, sharey=True) ax = axes.ravel() ax[0].imshow(image, cmap=plt.cm.gray, interpolation='nearest') ax[0].set_title("Original")
from scipy import ndimage import matplotlib.pyplot as plt from skimage.morphology import watershed, disk from skimage import data # original data from skimage.filter import rank image = data.camera() # denoise image denoised = rank.median(image, disk(2)) # find continuous region (low gradient) --> markers markers = rank.gradient(denoised, disk(5)) < 10 markers = ndimage.label(markers)[0] #local gradient gradient = rank.gradient(denoised, disk(2)) # process the watershed labels = watershed(gradient, markers) # display results fig, axes = plt.subplots(ncols=4, figsize=(8, 2.7)) ax0, ax1, ax2, ax3 = axes ax0.imshow(image, cmap=plt.cm.gray, interpolation='nearest') ax1.imshow(gradient, cmap=plt.cm.spectral, interpolation='nearest') ax2.imshow(markers, cmap=plt.cm.spectral, interpolation='nearest')
def segmentation(sample): samples = [] cores = [] images = [] cf = .9 entropy_ratio = .5 core_ratio = .07 #around 10% of image is core eq_thresh = 10 csize = 300 #change it later # for sample in samples: # if image_number<5: # image_number += 1 # continue # image_number += 1 try: gray_images = np.array([i for i in open_image(sample)]) except: print 'can\'t open' # continue m, n = gray_images[0].shape g_min = np.min(gray_images[1:], axis=0) g_max = np.max(gray_images[1:], axis=0) g_avg = np.average(gray_images[1:], axis=0) g_mean = rank.mean_bilateral(g_max, disk(40)) images.append(g_max) selem = disk(5) diff = g_max-g_min diff1 = g_avg-g_min diff2 = g_max-g_avg h2 = histogram(diff2) ''' equalize image -> cores are white or black ''' equalized = img_as_ubyte(exposure.equalize_hist(diff)) #equalized = img_as_ubyte(exposure.equalize_hist(g_min))#g_min equalized = exposure.adjust_gamma(g_max,2) ##eq_mask = [] #equalized = img_as_ubyte(exposure.equalize_hist(mask)) #eq_mask = equalized<eq_thresh ''' local otsu ''' radius = 20 selem = disk(radius) local_otsu = rank.otsu(equalized, selem) # local_otsu = tmp<threshold_otsu(equalized) bg = diff<=local_otsu ent = rank.entropy(g_max*~bg, disk(35)) grad = rank.gradient(g_mean, disk(50)) tmp = ent*grad core_mask = tmp>(np.min(tmp)+(np.max(tmp)-np.min(tmp))*entropy_ratio) # # h = histogram(local_otsu) # cdf = 0 # t = g_min.shape[0]*g_min.shape[1]*core_ratio # # for i in range(len(h)): # cdf += h[i] # if cdf > t: # maxi = i # break # # core_mask = (local_otsu<maxi) ## imshow(core_mask) # ##cores = np.logical_and(eq_mask, core_mask) # ##imshow(eq_mask) # # # # lbl, num_lbl = ndi.label(core_mask) for i in range(1,num_lbl+1): ''' lbl==0 is background ''' c = np.where(np.max(lbl==i, axis=0)==True)[0] left = c[0] right = c[-1] c = np.where(np.max(lbl==i, axis=1)==True)[0] up = c[0] down = c[-1] # ''' # Don't consider edge cores # ''' # if left<csize/2 or right>n-csize/2: # continue # if up<csize/2 or down>m-csize/2: # continue # core = np.zeros((csize, csize)) h = down-up w = right-left middle_x = min(max((up+down)/2, csize/2),m-csize/2) middle_y = min(max((left+right)/2, csize/2), n-csize/2) # core = (core_mask*gray_images[0])[middle_x-csize/2:middle_x+csize/2, middle_y-csize/2:middle_y+csize/2] core = gray_images[0][middle_x-csize/2:middle_x+csize/2, middle_y-csize/2:middle_y+csize/2] core = exposure.adjust_gamma(core,.5) cores.append(core) return cores # print 'image', image_number # #if __name__=='__main__': # os.system('rm %s -R'%(output_dir)) # os.system('mkdir %s'%(output_dir)) # #os.system('mkdir %sres/021'%(input_dir)) # #os.system('mkdir %sres/041'%(input_dir)) # for i in range(len(cores)): # image_name = '%s/%i.png'%(output_dir, i) # imsave(image_name, cores[i])
`skimage.dilate` and `skimage.erode` are equivalent filters (see below for comparison). Here is an example of the classical morphological gray-level filters: opening, closing and morphological gradient. """ from skimage.filter.rank import maximum, minimum, gradient noisy_image = img_as_ubyte(data.camera()) closing = maximum(minimum(noisy_image, disk(5)), disk(5)) opening = minimum(maximum(noisy_image, disk(5)), disk(5)) grad = gradient(noisy_image, disk(5)) # display results fig = plt.figure(figsize=[10, 7]) plt.subplot(2, 2, 1) plt.imshow(noisy_image, cmap=plt.cm.gray) plt.title('Original') plt.axis('off') plt.subplot(2, 2, 2) plt.imshow(closing, cmap=plt.cm.gray) plt.title('Gray-level closing') plt.axis('off') plt.subplot(2, 2, 3)
# applique une normalisation adaptive a contraste limitee de l'histogramme # (CLAHE) polDia_clahe = exposure.equalize_adapthist(polDia_med, clip_limit=0.03) polDia_clahe_stretch = exposure.rescale_intensity(polDia_clahe, out_range=(0, 256)) #revient a faire polDia_clahe multiplie par 256 plt.subplot(3,3,4) plt.title("CLAHE") plt.imshow(polDia_clahe_stretch,cmap = plt.cm.gray) plt.colorbar() # applique un gradient sur l'image floutee : mise en evidence des changements #de niveau abrupt polDia_grad = rank2.gradient(polDia_clahe_stretch,disk(3)) plt.subplot(3,3,5) plt.title("Suivi d'un filtre gradient") plt.imshow(polDia_grad,cmap = plt.cm.gray) plt.colorbar() type(polDia_grad) # Binarisation de l'image en la partie inferieur a un certain gradient #et l'autre polDia_grad_mark = polDia_grad<20 plt.subplot(3,3,6) plt.title("Selection d'un grandient mini") plt.imshow(polDia_grad_mark,cmap = plt.cm.gray)
if(test_flag < 1 and label_count ==1): mypic = np.transpose(ffts[file_idx]) mypic_rev = np.zeros_like(mypic) for i in range(mypic.shape[0]): mypic_rev[i] = mypic[-i - 1] mypic_rev_small = mypic_rev[:200,:] mypic_rev = mypic_rev_small mypic_rev_log = np.log10(mypic_rev+ 0.001) mypic_rev_gauss =sp.ndimage.gaussian_filter(mypic_rev, sigma=3) mypic_rev_log_gauss = sp.ndimage.gaussian_filter(mypic_rev_log, sigma=3) mypic_rev_gauss_bin = mypic_rev_gauss > np.percentile(mypic_rev_gauss,p) mypic_rev_log_gauss_bin = mypic_rev_log_gauss > np.percentile(mypic_rev_log_gauss,p) mypic_rev_gauss_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_gauss_bin)) mypic_rev_log_gauss_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_log_gauss_bin)) mypic_rev_gauss_grad = rank.gradient(pic_to_ubyte(mypic_rev_gauss), disk(3)) mypic_rev_log_gauss_grad = rank.gradient(pic_to_ubyte(mypic_rev_log_gauss), disk(3)) mypic_rev_gauss_grad_bin = mypic_rev_gauss_grad > np.percentile(mypic_rev_gauss_grad,p) mypic_rev_log_gauss_grad_bin = mypic_rev_log_gauss_grad > np.percentile(mypic_rev_log_gauss_grad,p ) mypic_rev_gauss_grad_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_gauss_grad_bin)) mypic_rev_log_gauss_grad_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_log_gauss_grad_bin)) bfh = sp.ndimage.binary_fill_holes(mypic_rev_gauss_grad_bin_close) bfh_rm = remove_small_objects(bfh, MIN_SEGMENT_SIZE) log_bfh = sp.ndimage.binary_fill_holes(mypic_rev_log_gauss_grad_bin_close) log_bfh_rm = remove_small_objects(log_bfh, MIN_SEGMENT_SIZE) # plt.subplot(6,2,1) # plt.imshow(mypic_rev,cmap=plt.cm.afmhot_r) # plt.axis('off') # plt.title('Spectrogram') # plt.subplot(6,2,2)