def filter_channel(im): '''Compute filtered versions of an image Parameters ---------- im : ndarray input image (2D) Returns ------- fs : ndarray filtered version of the image (3D array) ''' import numpy as np import mahotas as mh Tg = im > im.mean() T2g = im > (im.mean() + 2*im.std()) zim = im-im.mean() zim /= im.std() z8 = mh.gaussian_filter(zim, 8) z4 = mh.gaussian_filter(zim, 4) z12 = mh.gaussian_filter(zim, 12) z16 = mh.gaussian_filter(zim, 16) zdiff = z16 - z8 sob = mh.sobel(im, just_filter=True) return np.dstack([ Tg, T2g, zim, z4, z8, z12, z16, zdiff, sob])
def create_ring(self): im = self._image # This breaks up the image into RGB channels r, g, b = im.transpose(2, 0, 1) h, w = r.shape # smooth the image per channel: r12 = mh.gaussian_filter(r, 12.) g12 = mh.gaussian_filter(g, 12.) b12 = mh.gaussian_filter(b, 12.) # build back the RGB image im12 = mh.as_rgb(r12, g12, b12) X, Y = np.mgrid[:h, :w] X = X - h / 2. Y = Y - w / 2. X /= X.max() Y /= Y.max() # Array C will have the highest values in the center, fading out to the edges: C = np.exp(-2. * (X ** 2 + Y ** 2)) C -= C.min() C /= C.ptp() C = C[:, :, None] # The final result is sharp in the centre and smooths out to the borders: ring = mh.stretch(im * C + (1 - C) * im12) return ring
def test_float_input(): "[watershed]: Compare floating point input with integer input" f = np.random.random((128,64)) f = mh.gaussian_filter(f, 8.) f = mh.gaussian_filter(f, 8.) markers,_ = mh.label(mh.regmin(f)) f = np.round(f * 2**30) wf = mh.cwatershed(f / 2**30., markers) w32 = mh.cwatershed(f.astype(np.int32), markers) assert (wf == w32).mean() > .999
def pixel_features(histone, dna, rois): ''' features,labels = pixel_features(histone, dna, rois, scale) features = pixel_features(histone, dna, None, scale) Parameters ---------- histone : ndarray dna : ndarray rois : ndarray or None Returns ------- features : ndarray 2D array features for each region labels : ndarray (only if ``rois is not None``) for the corresponding region, returns the fraction of NETs ''' import numpy as np import mahotas as mh if rois is not None: rois = (rois > 0) rois = rois.astype(float) rois = mh.gaussian_filter(rois, 8) fs = np.dstack((filter_channel(histone), filter_channel(dna))) step = 8 fs = fs[16::step, 16::step] fs = fs.reshape((-1,fs.shape[-1])) fs = np.hstack((np.ones([len(fs),1]), fs)) if rois is None: return fs labels = rois[16::step, 16::step] labels = labels.ravel() return fs, labels
def test_find_edge(): import mahotas as mh f = np.zeros((32,48)) f[:,16:] = 255 f = mh.gaussian_filter(f,4) fs = sobel(f) assert np.all(fs[:,15] > 0)
def smooth(self, sigma, inplace=True): '''Applies a Gaussian smoothing filter to the pixels array. Parameters ---------- sigma: int size of the standard deviation of the Gaussian kernel inplace: bool, optional smooth the array inplace instead of returning a copy (default: ``True``) Returns ------- tmlib.image.Image smoothed image ''' array = mh.gaussian_filter(self.array, sigma) if inplace: self.array = array self.metadata.is_smoothed = True return self else: new_img = self.__class__(array, self.metadata) new_img.metadata.is_smoothed = True return new_img
def method2(image, sigma): image = mh.imread(image)[:, :, 0] image = mh.gaussian_filter(image, sigma) image = mh.stretch(image) binimage = image > mh.otsu(image) labeled, _ = mh.label(binimage) return labeled
def get_green_image(img): imghsv = skimage.color.rgb2hsv(img) greenpixels = (imghsv[:,:,0] > .2) * (imghsv[:,:,0] < .7) * (imghsv[:,:,1] > .18) greenpixels = mh.gaussian_filter(greenpixels, 2) > .5 alpha = np.ones(img.shape[0:2]).astype('uint8') * 255 img = np.dstack((img[:,:,0], img[:,:,1], img[:,:,2], alpha)) img[-greenpixels] = [255,255,255,0] return img
def _segment(histone): markers = np.zeros_like(histone) markers[16::32, 16::32] = 1 markers, _ = mh.label(markers) regions = mh.cwatershed(histone.max() - mh.gaussian_filter(histone, 1.2).astype(int), markers) sizes = mh.labeled.labeled_size(regions.astype(np.intc)) invalid, = np.where(sizes < 512) return mh.labeled.relabel(mh.labeled.remove_regions(regions.astype(np.intc), invalid))
def center_focus(im,f): r, g, b = im.transpose(2,0,1) r12 = mh.gaussian_filter(r, 12.0) g12 = mh.gaussian_filter(g, 12.0) b12 = mh.gaussian_filter(b, 12.0) im12 = mh.as_rgb(r12,g12,b12) h, w = r.shape Y, X = np.mgrid[:h,:w] Y = Y-h/2.0 Y = Y/Y.max() X = X-w/2.0 X = X/X.max() W = np.exp(-2.0*(X**2 + Y**2)/0.5) W = W - W.min() W = W/W.ptp() W = W[:, :, None] ringed = mh.stretch(im*W + (1.0-W)*im12) plt.imshow(ringed) plt.savefig(f) plt.show ()
def peppers(): # This last image is the peppers.png file my_image = mh.imread(filename3) T = mh.otsu(my_image) b_image = (my_image > T) g_image = mh.gaussian_filter(b_image, 15) rmax = mh.regmax(g_image) labeled, nr_objects = mh.label(rmax) centers = mh.center_of_mass(my_image, labeled)[1:] print "The peppers.png file contains ", nr_objects, " objects." o = 1 for center in centers: print "Object %s center: [ %s, %s ]" %(o, round(center[1], 0), round(center[0], 0)) o = o + 1
def objects(): # The second image is the objects.png file #import image from file my_image = mh.imread(filename2) #use the mean to form a binary image b_image = (my_image > my_image.mean()) #use gaussian filter g_image = mh.gaussian_filter(b_image, 1.5) #count the number of objects in the picture labeled, nr_objects = mh.label(g_image) #find center point for each object centers = mh.center_of_mass(my_image, labeled)[1:] print "The objects.png contains ", nr_objects, " objects." o = 1 for center in centers: print "Object %s center: [ %s, %s ]" %(o, round(center[1], 0), round(center[0], 0)) o = o + 1
def _segment(cell): # takes a numpy array of a microscopy # segments it based on filtering the image then applying a distance transform and # a watershed method to get the proper segmentation import mahotas as mh filt_cell = mh.gaussian_filter(cell, 2) T = mh.thresholding.otsu((np.rint(filt_cell).astype('uint8'))) dist = mh.stretch(mh.distance(filt_cell > T)) Bc = np.ones((3,3)) rmax = mh.regmin((dist)) rmax = np.invert(rmax) labels, num_cells = mh.label(rmax, Bc) surface = (dist.max() - dist) areas = mh.cwatershed(dist, labels) areas *= T return areas
def segment(fname): dna = mh.imread(fname) dna = dna[:,:,0] sigma = 12. dnaf = mh.gaussian_filter(dna, sigma) T_mean = dnaf.mean() bin_image = dnaf > T_mean labeled, nr_objects = mh.label(bin_image) maxima = mh.regmax(mh.stretch(dnaf)) maxima = mh.dilate(maxima, np.ones((5,5))) maxima,_ = mh.label(maxima) dist = mh.distance(bin_image) dist = 255 - mh.stretch(dist) watershed = mh.cwatershed(dist, maxima) watershed *= bin_image return watershed
def get_building_image(img): bldg = (img[:,:,0]==242) * (img[:,:,1]==240) * (img[:,:,2]==233) bldg2 = (img[:,:,0]==242) * (img[:,:,1]==238) * (img[:,:,2]==226) bldg3 = (img[:,:,0]==244) * (img[:,:,1]==242) * (img[:,:,2]==234) bldg4 = (img[:,:,0]==210) * (img[:,:,1]==210) * (img[:,:,2]==217) bldg5 = (img[:,:,0]==248) * (img[:,:,1]==248) * (img[:,:,2]==240) bldg6 = (img[:,:,0]==217) * (img[:,:,1]==217) * (img[:,:,2]==217) bldg7 = (img[:,:,0]==203) * (img[:,:,1]==202) * (img[:,:,2]==213) bldg8 = (img[:,:,0]==242) * (img[:,:,1]==242) * (img[:,:,2]==234) bldg9 = (img[:,:,0]==255) * (img[:,:,1]==255) * (img[:,:,2]==255) bldg10 = (img[:,:,0]==251) * (img[:,:,1]==247) * (img[:,:,2]==242) bldg11 = (img[:,:,0]==210) * (img[:,:,1]==207) * (img[:,:,2]==217) # TODO also ugh. bldg_pixels = bldg + bldg2 + bldg3 + bldg4 + bldg5 + bldg6 + bldg7 + bldg8 + bldg9 + bldg10 + bldg11 bldg_pixels = mh.gaussian_filter(bldg_pixels, 2) > .5 alpha = np.ones(img.shape[0:2]).astype('uint8') * 255 img = np.dstack((img[:,:,0], img[:,:,1], img[:,:,2], alpha)) img[-bldg_pixels] = [0,0,0,0] img[bldg_pixels] = [55, 126, 184, 255] return img
def circles(): # Image 1 is the circles.png file my_image = mh.imread(filename) # Threshold using the Riddler-Calvard method # More on Riddler-Calvard: http://mahotas.readthedocs.org/en/latest/thresholding.html thres = mh.rc(my_image) #use the value to form a binary image b_image = (my_image > thres) #use gaussian filter g_image = mh.gaussian_filter(b_image, 33) #separate objects stuck together rmax = mh.regmax(g_image) #count the number of objects in the picture labeled, nr_objects = mh.label(rmax) #find center point for each object centers = mh.center_of_mass(my_image, labeled)[1:] print "The circles.png file contains ", nr_objects, " objects." o = 1 for center in centers: print "Object %s center: %s" %(o, center) o = o + 1
def surf_grid(red, green, rois, scale): ''' features,labels = surf_grid(histone, dna, rois, scale) features = surf_grid(histone, dna, None, scale) Parameters ---------- histone : ndarray dna : ndarray rois : ndarray or None Returns ------- features : ndarray 2D array features for each region labels : ndarray (only if ``rois is not None``) for the corresponding region, returns the fraction of NETs ''' import mahotas.features.surf import mahotas as mh import numpy as np locations = [(x,y,scale,1.,1.) for x in range(32,512,8) for y in range(32,512,8)] rfeatures = mahotas.features.surf.descriptors(red, locations, descriptor_only=False) gfeatures = mahotas.features.surf.descriptors(green, locations, descriptor_only=True) features = np.hstack((rfeatures, gfeatures)) positions = features[:,:2].astype(int) features = features[:,5:] features.T[0] = 1 if rois is None: return features rois = (rois > 0) rois = rois.astype(float) rois = mh.gaussian_filter(rois, 8) labels = np.array([rois[a,b] for a,b in positions]) return features, labels
import mahotas as mh import numpy as np from matplotlib import pyplot as plt # Load image & convert to B&W image = mh.imread('AbelSimpleImageDataset/1.jpg') image = mh.colors.rgb2grey(image, dtype=np.uint8) plt.imshow(image) plt.gray() plt.title('original image') thresh = mh.thresholding.otsu(image) print('Otsu threshold is {}.'.format(thresh)) threshed = (image > thresh) plt.figure() plt.imshow(threshed) plt.title('threholded image') mh.imsave('data/thresholded.png', threshed.astype(np.uint8) * 255) im16 = mh.gaussian_filter(image, 16) # Repeat the thresholding operations with the blurred image thresh = mh.thresholding.otsu(im16.astype(np.uint8)) threshed = (im16 > thresh) plt.figure() plt.imshow(threshed) plt.title('threholded image (after blurring)') print('Otsu threshold after blurring is {}.'.format(thresh)) mh.imsave('data/thresholded16.png', threshed.astype(np.uint8) * 255) plt.show()
def test_gaussian_order(): im = np.arange(64 * 64).reshape((64, 64)) for order in (1, 2, 3): g_mat = mahotas.gaussian_filter(im, 2., order=order)
import numpy as np import mahotas as mh image = mh.imread('scene00.jpg') from matplotlib import pyplot as plt plt.imshow(image) plt.show() image = mh.colors.rgb2grey(image, dtype=np.uint8) plt.imshow(image) # Display the image plt.gray() thresh = mh.thresholding.otsu(image) print('Otsu threshold is {}.'.format(thresh)) # Otsu 경계 값은 138이다 plt.imshow(image > thresh) im16 = mh.gaussian_filter(image, 16) im = mh.demos.load('lenna') r, g, b = im.transpose(2, 0, 1) r12 = mh.gaussian_filter(r, 12.) g12 = mh.gaussian_filter(g, 12.) b12 = mh.gaussian_filter(b, 12.) im12 = mh.as_rgb(r12, g12, b12) h, w = r.shape # 높이와 폭 Y, X = np.mgrid[:h, :w] Y = Y - h / 2. # h/2에 중앙화 Y = Y / Y.max() # -1 .. +1로 정규화 X = X - w / 2. X = X / X.max()
#print(image_uint8) #print(image_float) thresh = mh.thresholding.otsu(image) otsubin = (image_uint8 > thresh) otsubin = mh.open(otsubin, np.ones((15,15))) views = [] view_titles = [] views.append(otsubin) view_titles.append('Otsu w/ open') for sigma in (8, 16, 32): im = mh.gaussian_filter(image_uint8, sigma) # print(im) views.append(im > thresh) view_titles.append('Sigma = ' + str(sigma)) # Initial view index = 0 f = Figure() a = f.add_subplot(111) a.imshow(views[index], cmap = cm.Greys_r) a.set_title(view_titles[index]) #/\#/\# # a tk.DrawingArea canvas = FigureCanvasTkAgg(f, master=root)
def process_image(im, d, test=False, remove_bordering=False): plt.figure(1, frameon=False) sigma = 75 blurred = mh.gaussian_filter(im.astype(float), sigma) T_mean = blurred.mean() bin_image = im > T_mean maxima = mh.regmax(mh.stretch(blurred)) maxima, _ = mh.label(maxima) dist = mh.distance(bin_image) dist = 255 - mh.stretch(dist) watershed = mh.cwatershed(dist, maxima) _, old_nr_objects = mh.labeled.relabel(watershed) sizes = mh.labeled.labeled_size(watershed) min_size = 100000 filtered = mh.labeled.remove_regions_where( watershed * bin_image, sizes < min_size) _, nr_objects = mh.labeled.relabel(filtered) print('Removed', old_nr_objects - nr_objects, 'small regions') old_nr_objects = nr_objects if (remove_bordering): filtered = mh.labeled.remove_bordering(filtered) labeled, nr_objects = mh.labeled.relabel(filtered) print('Removed', old_nr_objects - nr_objects, 'bordering cells') print("Number of cells: {}".format(nr_objects)) fin_weights = mh.labeled_sum(im.astype(np.uint32), labeled) fin_sizes = mh.labeled.labeled_size(labeled) fin_result = fin_weights / fin_sizes if (test): f, axarr = plt.subplots(2, 2) for i in range(2): for j in range(2): axarr[i][j].axis('off') axarr[0, 0].imshow(im) axarr[0, 0].set_title('Source') axarr[0, 1].imshow(labeled) axarr[0, 1].set_title('Labeled') axarr[1, 0].imshow(watershed) axarr[1, 0].set_title('Watershed') axarr[1, 1].imshow(blurred) axarr[1, 1].set_title('Blurred') for i in range(1, nr_objects + 1): print("Cell {} average luminescence is {}".format( i, fin_result[i])) bbox = mh.bbox((labeled == i)) plt.text((bbox[2] + bbox[3]) / 2, (bbox[0] + bbox[1] ) / 2, str(i), fontsize=20, color='black') # plt.show() plt.savefig("test" + str(nr_objects) + ".svg", format='svg', bbox_inches='tight', dpi=1200) else: for i in range(1, nr_objects + 1): bbox = mh.bbox((labeled == i)) cell = (im * (labeled == i))[bbox[0]:bbox[1], bbox[2]:bbox[3]] hashed = hashlib.sha1(im).hexdigest() imsave(d + data_dir + hashed + '-' + str(i) + '.png', imresize(cell, (img_rows, img_cols)))
import mahotas as mh import numpy as np import cv2 # Imported mahotas & numpy with standard abbreviations im = mh.imread('./images/pool-table-above-17031042.jpg', as_grey=1) # Load the image & convert to gray # im2 = im[::2,::2] im2 = mh.gaussian_filter(im, 1.2) cv2.imshow('gaussian', im) # save first step # mh.imsave('1.png', im2.astype(np.uint8)) # Mean filtering is implemented "by hand" with a convolution. mean_filtered = mh.convolve(im2.astype(float), np.ones((9, 9))/81.) # iminv = 255 - mean_filtered # mh.imsave('binarized1.png', iminv.astype(np.uint8)) # You might need to adjust the number 4 here, but it worked well for this image. imc = im2 > mean_filtered - 4 # cv2.imshow('open circles', (imc*255).astype(np.uint8)); # cv2.waitKey(0) # mh.imsave('1.png', im2.astype(np.uint8)) # print(im2) # imc = mh.convolve(imc.astype(float), np.ones((9, 9))/81.) # imc = im2 > mean_filtered - 6
import mahotas from os import path import numpy as np from matplotlib import pyplot as plt try: nuclear_path = path.join(path.dirname(path.abspath(__file__)), 'data', 'nuclear.png') except NameError: nuclear_path = path.join('data', 'nuclear.png') nuclear = mahotas.imread(nuclear_path) nuclear = nuclear[:, :, 0] nuclear = mahotas.gaussian_filter(nuclear, 1.) threshed = (nuclear > nuclear.mean()) distances = mahotas.stretch(mahotas.distance(threshed)) Bc = np.ones((9, 9)) maxima = mahotas.morph.regmax(distances, Bc=Bc) spots, n_spots = mahotas.label(maxima, Bc=Bc) surface = (distances.max() - distances) areas = mahotas.cwatershed(surface, spots) areas *= threshed import random from matplotlib import colors as c from matplotlib import cm colors = [cm.jet(c) for c in range(0, 256, 4)] random.shuffle(colors) colors[0] = (0., 0., 0., 1.) rmap = c.ListedColormap(colors)
import mahotas as mh import numpy as np im = mh.imread('lenna.jpg') r,g,b = im.transpose(2,0,1) h,w = r.shape r12 = mh.gaussian_filter(r, 12.) g12 = mh.gaussian_filter(g, 12.) b12 = mh.gaussian_filter(b, 12.) im12 = mh.as_rgb(r12,g12,b12) X,Y = np.mgrid[:h,:w] X = X-h/2. Y = Y-w/2. X /= X.max() Y /= Y.max() C = np.exp(-2.*(X**2+ Y**2)) C -= C.min() C /= C.ptp() C = C[:,:,None] ring = mh.stretch(im*C + (1-C)*im12) mh.imsave('lenna-ring.jpg', ring)
def split_new(image, binary): ''' ''' bbox = mh.bbox(binary) sub_image = np.array(image[bbox[0]:bbox[1], bbox[2]:bbox[3]]) sub_binary = np.array(binary[bbox[0]:bbox[1], bbox[2]:bbox[3]]) sub_binary_border = mh.labeled.borders(sub_binary, Bc=mh.disk(3)) sub_binary = mh.erode(sub_binary.astype(np.bool)) for e in range(5): sub_binary = mh.erode(sub_binary) # sub_binary = mh.erode(sub_binary) if sub_image.shape[0] < 2 or sub_image.shape[1] < 2: return np.zeros(binary.shape, dtype=np.bool), np.zeros(binary.shape, dtype=np.bool) # # smooth the image # sub_image = mh.gaussian_filter(sub_image, 3.5) grad_x = np.gradient(sub_image)[0] grad_y = np.gradient(sub_image)[1] grad = np.add(np.abs(grad_x), np.abs(grad_y)) grad -= grad.min() grad /= grad.max() grad *= 255 grad = grad.astype(np.uint8) coords = zip(*np.where(sub_binary==1)) if len(coords) < 2: print 'STRAAAAANGE' return np.zeros(binary.shape, dtype=np.bool), np.zeros(binary.shape, dtype=np.bool) seed1 = random.choice(coords) seed2 = random.choice(coords) seeds = np.zeros(sub_binary.shape, dtype=np.uint64) seeds[seed1] = 1 seeds[seed2] = 2 for i in range(10): seeds = mh.dilate(seeds) ws = mh.cwatershed(grad, seeds) ws[sub_binary==0] = 0 # ws_relabeled = skimage.measure.label(ws.astype(np.uint8)) # ws_relabeled[sub_binary==0] = 0 # max_label = ws_relabeled.max() # plt.figure() # imshow(ws) binary_mask = Util.threshold(ws, ws.max()) border = mh.labeled.border(ws, ws.max(), ws.max()-1, Bc=mh.disk(2)) # border[sub_binary_border == 1] = 0 # remove any "real" border pixels # plt.figure() # imshow(binary_mask) # plt.figure() # imshow(border) large_label = np.zeros(binary.shape, dtype=np.bool) large_border = np.zeros(binary.shape, dtype=np.bool) large_label[bbox[0]:bbox[1], bbox[2]:bbox[3]] = binary_mask large_border[bbox[0]:bbox[1], bbox[2]:bbox[3]] = border return large_label, large_border
import mahotas import numpy as np import matplotlib.pyplot as plt import os plt.subplot(3, 2, 1) f = mahotas.imread(os.path.join('data', 'nuclear.png')) f = f[:, :, 0] plt.title('input image, first channel') plt.imshow(f) plt.subplot(3, 2, 2) f = mahotas.gaussian_filter(f, 4) f = (f > f.mean()) plt.title('gaussian_filter') plt.imshow(f) plt.subplot(3, 2, 3) labeled, n_nucleus = mahotas.label(f) plt.title('Found {} nuclei.'.format(n_nucleus)) plt.imshow(labeled) plt.subplot(3, 2, 4) sizes = mahotas.labeled.labeled_size(labeled) too_big = np.where(sizes > 10000) labeled = mahotas.labeled.remove_regions(labeled, too_big) plt.title('remove_regions') plt.imshow(labeled) plt.subplot(3, 2, 5) labeled = mahotas.labeled.remove_bordering(labeled)
import mahotas as mh import numpy as np im = mh.imread('lenna.jpg') r, g, b = im.transpose(2, 0, 1) h, w = r.shape r12 = mh.gaussian_filter(r, 12.) g12 = mh.gaussian_filter(g, 12.) b12 = mh.gaussian_filter(b, 12.) im12 = mh.as_rgb(r12, g12, b12) X, Y = np.mgrid[:h, :w] X = X - h / 2. Y = Y - w / 2. X /= X.max() Y /= Y.max() C = np.exp(-2. * (X**2 + Y**2)) C -= C.min() C /= C.ptp() C = C[:, :, None] ring = mh.stretch(im * C + (1 - C) * im12) mh.imsave('lenna-ring.jpg', ring)
def metricscale(leafimage, minticks, scaleunits, equalize=False, blur=False): "Find the ruler marks along one edge of a binary image, in mm, and calculate the scale in cm per pixel." # Must have at least minticks tick marks along one edge # Input: # file: a string containing the path and file name for an image file # minticks: must have at least this number of tick marks in the scale along one edge of the image # in order to be considered to be reliable. The default is 10. # Output: # scale: cm (or inches) per pixel in the image. This is a floating point number. # found: whether or not at least minticks ruled marks were found along at least one edge. # This is a boolean. # edge: edge along which ruled marks were found. Either 'L', 'R', 'T', or 'B' for # left, right, top, or bottom. # leafimage = imread.imread(file, as_grey=True) # leafimage = mh.demos.nuclear_image() # print 'before equalization, min = ', np.amin(leafimage), ', max = ', np.amax(leafimage) if equalize: leafimage = exposure.equalize_hist(leafimage / 255.0) * 255.0 # pylab.imshow(leafimage, cmap=cm.gray) # print 'after equalization, min = ', np.amin(leafimage), ', max = ', np.amax(leafimage) if blur: leafimage = mh.gaussian_filter(leafimage, 4) threshold = mh.otsu(leafimage.astype(np.uint8)) # print 'threshold = ', threshold leafimagebw = (leafimage > threshold) # convert to BW image # pylab.imshow(leafimagebw, cmap=cm.gray, vmin=0, vmax=1) # Find the edge with the scale n, m = leafimage.shape leftright = [ 5, m - 5 ] # five pixels in from left and right edges, to avoid noise at image edges topbottom = [5, n - 5] # five pixels in from top and bottom edges found = False edge = '' # Check left and right edges for ruler marks for i in topbottom: up = array.array( 'L', []) # pixel locations where leafimage values go from 0 to 1. down = array.array( 'L', []) # pixel locations where leafimage values go from 1 to 0. for j in range(1, m - 1): if leafimagebw[i, j] < leafimagebw[i, j + 1]: up.append(j) elif leafimagebw[i, j] > leafimagebw[i, j + 1]: down.append(j) # The float variable, scale, is the number of pixels per cm. if i == 5: foundtop, scale = foundscale( up, down, n, m, minticks, scaleunits) # Are ruler marks on top edge? if foundtop: # no need to search any of the other edges for ruler marks. found = True edge = 'T' break else: foundbottom, scale = foundscale( up, down, n, m, minticks, scaleunits) # Are ruler marks on bottom edge? if foundbottom: found = True edge = 'B' # If the ruler marks are not on the top or the bottom edges, check the left and the right if not found: downcounter = 0 # number of times that leafimage value goes from 1 to 0. upcounter = 0 # number of times that leafimage value goes from 0 to 1. side = -1 # is this the right side or left side? for j in leftright: up = array.array( 'L', []) # pixel locations where leafimage values go from 0 to 1. down = array.array( 'L', []) # pixel locations where leafimage values go from 1 to 0. for i in range(1, n - 1): if leafimagebw[i, j] < leafimagebw[i + 1, j]: up.append(i) elif leafimagebw[i, j] > leafimagebw[i + 1, j]: down.append(i) # The float variable, scale, is the number of pixels per cm. if j == 5: foundleft, scale = foundscale( up, down, n, m, minticks, scaleunits) # Are ruler marks on left edge? if foundleft: # no need to search any of the other edges for ruler marks. found = True edge = 'L' break else: foundright, scale = foundscale( up, down, n, m, minticks, scaleunits) # Are ruler marks on right edge? if foundright: found = True edge = 'R' # pylab.imshow(leafimage) return (scale, found, edge)
def Measure_Motion(fpath, crop, mt_cutoff, SIGMA): #Extract ycrop value try: #if passed as x,y coordinates if len(crop.data['y']) != 0: ycrop = int(np.around(crop.data['y'][0])) else: ycrop = 0 except: #if passed as single value ycrop = crop #Upoad file cap = cv2.VideoCapture(fpath) #Get maxiumum frame of file. Note that this is updated later if fewer frames detected cap_max = int(cap.get(7)) #7 is index of total frames #Set first frame to be grabbed cap.set( 1, 0 ) #first index references frame property, second specifies next frame to grab #Initialize first frame ret, frame = cap.read() frame_new = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame_new = frame_new[ycrop:, :] frame_new = mh.gaussian_filter(frame_new, sigma=SIGMA) #Initialize vector to store motion values in Motion = np.zeros(cap_max) #Loop through frames to detect frame by frame differences for x in range(1, cap_max): #Reset old frame frame_old = frame_new #Attempt to load next frame ret, frame = cap.read() if ret == True: #Reset new frame and process frame_new = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame_new = frame_new[ycrop:, :] frame_new = mh.gaussian_filter( frame_new, sigma=SIGMA ) # used to reduce influence of jitter from one frame to the next #Calculate difference between frames frame_dif = np.absolute(frame_new - frame_old) frame_cut = frame_dif > mt_cutoff frame_cut = frame_cut.astype('uint8') #Assign difference to array Motion[x] = np.sum(frame_cut) else: #if no frame is detected cap_max = (x - 1) #Reset max frame to last frame detected Motion = Motion[:cap_max] #Amend length of motion vector break print('total frames: ' + str(cap_max)) #release video cap.release() #return motion values return (Motion)
def test_gaussian_small_image(): np.random.seed(123) f = (np.random.random((10, 141)) * 255).astype(np.uint8) ff = mh.gaussian_filter(f, 2.) assert f.shape == ff.shape
def PlayVideo(fpath, fps, start, end, img_scale, save_video, Freezing, mt_cutoff, crop, SIGMA): #Extract ycrop value try: #if passed as x,y coordinates if len(crop.data['y']) != 0: ycrop = int(np.around(crop.data['y'][0])) else: ycrop = 0 except: #if passed as single value ycrop = crop #Upoad file cap = cv2.VideoCapture(fpath) #redfine start/end in frames fstart = start #*fps fend = end #*fps #set play speed and define first frame rate = int(1000 / fps) #duration each frame is present for, in milliseconds cap.set(1, fstart) #set reference position of first frame to 0 #set text parameters textfont = cv2.FONT_HERSHEY_SIMPLEX textposition = (10, 30) textfontscale = 1 textlinetype = 2 #Initialize first frame ret, frame = cap.read() frame_new = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame_new = frame_new[ycrop:, :] frame_new = mh.gaussian_filter(frame_new, sigma=SIGMA) #Initialize video storage if desired if save_video: width = int(frame.shape[1] * img_scale) height = int((frame.shape[0] + frame.shape[0] - ycrop) * img_scale) fourcc = cv2.VideoWriter_fourcc( *'jpeg') #only writes up to 20 fps, though video read can be 30. #fourcc = cv2.VideoWriter_fourcc(*'MJPG') #only writes up to 20 fps, though video read can be 30. writer = cv2.VideoWriter('out.avi', fourcc, 20.0, (width, height), isColor=False) #Loop through frames to detect frame by frame differences for x in range(fstart + 1, fend): # press 'q' to exit if cv2.waitKey(1) & 0xFF == ord('q'): break #Attempt to load next frame ret, frame = cap.read() if ret == True: #Convert to gray scale frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #set old frame to new frame frame_old = frame_new #Reset new frame and process frame_new = frame frame_new = frame_new[ycrop:, :] frame_new = mh.gaussian_filter( frame_new, sigma=SIGMA ) # used to reduce influence of jitter from one frame to the next #Calculate difference between frames frame_dif = np.absolute(frame_new - frame_old) frame_cut = frame_dif > mt_cutoff frame_cut = frame_cut.astype('uint8') * 255 #Add text to videos if Freezing[x] == 100: texttext = 'FREEZING' textfontcolor = 255 else: texttext = 'ACTIVE' textfontcolor = 255 cv2.putText(frame, texttext, textposition, textfont, textfontscale, textfontcolor, textlinetype) #Display video frame = cv2.resize(frame, (0, 0), fx=img_scale, fy=img_scale) frame_cut = cv2.resize(frame_cut, (0, 0), fx=img_scale, fy=img_scale) preview = np.concatenate((frame, frame_cut)) cv2.imshow("preview", preview) cv2.waitKey(rate) #Save video (if desired). if save_video: writer.write(preview) else: print('No frame detected at frame : ' + str(x) + '.Stopping video play') break #Close video window and video writer if open cv2.destroyAllWindows() _ = cv2.waitKey(1) if save_video: writer.release()
def test_gaussian_small_sigma(): im = np.arange(128 * 4).reshape((16, -1)) mh.gaussian_filter(im, .01)
def Calibrate(fpath, cal_sec, cal_pix, fps, SIGMA): #Upoad file cap = cv2.VideoCapture(fpath) #set seconds to examine and frames cal_frames = cal_sec * fps #Initialize matrix for difference values cal_dif = np.zeros((cal_frames, cal_pix)) #Initialize video cap.set( 1, 0 ) #first index references frame property, second specifies next frame to grab #Initialize first frame ret, frame = cap.read() frame_new = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame_new = mh.gaussian_filter(frame_new, sigma=SIGMA) #Get random set of pixels to examine across frames h, w = frame_new.shape h_loc = np.random.rand(cal_pix, 1) * h h_loc = h_loc.astype(int) w_loc = np.random.rand(cal_pix, 1) * w w_loc = w_loc.astype(int) #Loop through frames to detect frame by frame differences for x in range(1, cal_frames): #Reset old frame frame_old = frame_new #Load next frame ret, frame = cap.read() #Process frame frame_new = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame_new = mh.gaussian_filter( frame_new, sigma=SIGMA ) # used to reduce influence of jitter from one frame to the next #Get differences for select pixels frame_pix_dif = np.absolute(frame_new[h_loc, w_loc] - frame_old[h_loc, w_loc]) frame_pix_dif = frame_pix_dif[:, 0] #Populate difference array cal_dif[x, :] = frame_pix_dif percentile = np.percentile(cal_dif, 99.99) #Calculate grayscale change cutoff for detecting motion cal_dif_avg = np.nanmean(cal_dif) #Set Cutoff mt_cutoff = 2 * percentile #Print stats and selected cutoff print('Average frame-by-frame pixel difference: ' + str(cal_dif_avg)) print('99.99 percentile of pixel change differences: ' + str(percentile)) print('Grayscale change cut-off for pixel change: ' + str(mt_cutoff)) hist_freqs, hist_edges = np.histogram(cal_dif, bins=np.arange(30)) hist = hv.Histogram((hist_edges, hist_freqs)) hist.opts(title="Motion Cutoff: " + str(np.around(mt_cutoff, 1)), xlabel="Grayscale Change") vline = hv.VLine(mt_cutoff) vline.opts(color='red') return hist * vline
import mahotas as mh from os import path import numpy as np from matplotlib import pyplot as plt nuclear = mh.demos.load('nuclear') nuclear = nuclear[:, :, 0] nuclear = mh.gaussian_filter(nuclear, 1.) threshed = (nuclear > nuclear.mean()) distances = mh.stretch(mh.distance(threshed)) Bc = np.ones((9, 9)) maxima = mh.morph.regmax(distances, Bc=Bc) spots, n_spots = mh.label(maxima, Bc=Bc) surface = (distances.max() - distances) areas = mh.cwatershed(surface, spots) areas *= threshed import random from matplotlib import colors from matplotlib import cm cols = [cm.jet(c) for c in range(0, 256, 4)] random.shuffle(cols) cols[0] = (0., 0., 0., 1.) rmap = colors.ListedColormap(cols) plt.imshow(areas, cmap=rmap) plt.show()
# import numpy as np # import mahotas as mh # # image = mh.imread("C:/Users/Hyungi/Desktop/workplace/img/lena-ring.jpg") # from matplotlib import pyplot as plt # plt.imshow(image) # plt.show() # # image = mh.colors.rgb2grey(image, dtype=np.uint8) # plt.imshow(image) # plt.gray() # thresh = mh.thresholding.otsu(image) im16 = mh.gaussian_filter(image, 16) #주변컬러값 16개 plt.imshow(im16) plt.show() # 색깔이 뭉개져 import mahotas.demos wally = mahotas.demos.load('Wally') imshow(wally) show() wfloat = wally.astype(float) r, g, b = wfloat.transpose((2,0,1)) #transpose 시킴. 인덱스 번호는 0, 1, 2 순서로 갑니다. 그런데 지금 '2'가 면으로 왔습니다. ??????????????? w = wfloat.mean(2)# 2개씩 평균을 취해감.
import numpy as np import scipy import mahotas f = mahotas.imread('/home/krish/Pictures/labeled-2.png') f = mahotas.gaussian_filter(f, 4) f = (f> f.mean()) labeled, n_nucleus = mahotas.label(f) print('found {} nuclei.'.format(n_nucleus)) sizes = mahotas.labeled.labeled_size(labeled) too_big = np.where(sizes > 10000) labeled = mahotas.labeled.remove_regions(labeled, too_big) labeled = mahotas.labeled.remove_bordering(labeled) relabeled, n_left = mahotas.labeled.relabel(labeled) print('After filtering and relabeling, there are {} nuclei left.'.format(n_left))
def method1(image, sigma): image = mh.imread(image)[:, :, 0] image = mh.gaussian_filter(image, sigma) binimage = image > image.mean() labeled, _ = mh.label(binimage) return labeled
import numpy as np from matplotlib import pyplot as plt # 이미지 로드 & B&W로 변환 image = mh.imread('../SimpleImageDataset/scene00.jpg') image = mh.colors.rgb2grey(image, dtype=np.uint8) plt.imshow(image) plt.gray() plt.title('original image') thresh = mh.thresholding.otsu(image) print('Otsu threshold is {}.'.format(thresh)) threshed = (image > thresh) plt.figure() plt.imshow(threshed) plt.title('threholded image') mh.imsave('thresholded.png', threshed.astype(np.uint8)*255) im16 = mh.gaussian_filter(image, 16) # 블러링 이미지로 경계 연산 반복 thresh = mh.thresholding.otsu(im16.astype(np.uint8)) threshed = (im16 > thresh) plt.figure() plt.imshow(threshed) plt.title('threholded image (after blurring)') print('Otsu threshold after blurring is {}.'.format(thresh)) mh.imsave('thresholded16.png', threshed.astype(np.uint8)*255) plt.show()
# This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License import numpy as np import mahotas as mh image = mh.imread('../SimpleImageDataset/building05.jpg') image = mh.colors.rgb2gray(image) # Compute Gaussian filtered versions with increasing kernel widths im8 = mh.gaussian_filter(image, 8) im16 = mh.gaussian_filter(image, 16) im32 = mh.gaussian_filter(image, 32) # We now build a composite image with three panels: # # [ IM8 | | IM16 | | IM32 ] h, w = im8.shape canvas = np.ones((h, 3 * w + 256), np.uint8) canvas *= 255 canvas[:, :w] = im8 canvas[:, w + 128:2 * w + 128] = im16 canvas[:, -w:] = im32 mh.imsave('../1400OS_10_05+.jpg', canvas[:, ::2]) # Threshold the image # We need to first stretch it to convert to an integer image
def invert(array, smooth=False, sigma=2.5): grad = mh.gaussian_filter(array, sigma) return (255-grad)
def test_gaussian_small_image(): np.random.seed(123) f = (np.random.random((10,141))*255).astype(np.uint8) ff = mh.gaussian_filter(f, 2.) assert f.shape == ff.shape
def gaussian_order(order): mahotas.gaussian_filter(im, 2., order=order)
def split(self, input): ''' TODO: move to separate class ''' ### Image and Segmentation tile values = input['value'] tile = m.ObtainFullSizeImagesPanel(self.__u_info, self.__db, values["z"]) segtile = m.ObtainFullSizeIdsPanel(self.__u_info, self.__db, values["z"]) ############################### label_id = values['id'] # # crop according to bounding box # bbox = values['brush_bbox'] sub_tile = tile[bbox[2]:bbox[3],bbox[0]:bbox[1]] seg_sub_tile = segtile[bbox[2]:bbox[3],bbox[0]:bbox[1]] mh.imsave(self.__tmp_dojobox_tif, sub_tile); sub_tile = mh.gaussian_filter(sub_tile, 1).astype(np.uint8) # gaussian filter sub_tile = (255 * exposure.equalize_hist(sub_tile)).astype(np.uint8) # enhance contrast brush_mask = np.zeros((1024,1024),dtype=bool) brush_size = values['brush_size'] i_js = values['i_js'] # # Generate dense brush # dense_brush = [] for i in range(len(i_js)-1): # two sparse points p0 = i_js[i] p1 = i_js[i+1] # x and y coordinates of sparse points xp = [p0[1], p1[1]] if p0[1] < p1[1] else [p1[1], p0[1]] yp = [p0[0], p1[0]] if p0[1] < p1[1] else [p1[0], p0[0]] # linear interpolation between p0 and p1 xs = [x for x in range(xp[0], xp[1]+1)] ys = np.round(np.interp(xs, xp, yp)).astype(np.int32) # add linear interpolation to brush stroke dense_brush += zip(ys,xs) # make x axis dense # x and y coordinates of sparse points xp = [p0[1], p1[1]] if p0[0] < p1[0] else [p1[1], p0[1]] yp = [p0[0], p1[0]] if p0[0] < p1[0] else [p1[0], p0[0]] # linear interpolation between p0 and p1 ys = [y for y in range(yp[0], yp[1]+1)] xs = np.round(np.interp(ys, yp, xp)).astype(np.int32) # add linear interpolation to brush stroke dense_brush += zip(ys,xs) # dense_brush = list(set(dense_brush)) # add dense brush stroke to mask image brush_mask = np.zeros((1024,1024),dtype=bool) # for c in i_js: for c in dense_brush: brush_mask[c[1],c[0]] = True # crop brush_mask = brush_mask[bbox[2]:bbox[3],bbox[0]:bbox[1]] brush_mask = mh.morph.dilate(brush_mask, np.ones((2*brush_size, 2*brush_size))) brush_image = np.copy(sub_tile) brush_image[~brush_mask] = 0 # compute frame frame = np.zeros(brush_mask.shape,dtype=bool) frame[0,:] = True frame[:,0] = True frame[-1,:] = True frame[:,-1] = True # dilate non-brush segments outside_brush_mask = np.copy(~brush_mask) outside_brush_mask = mh.morph.dilate(outside_brush_mask, np.ones((brush_size, brush_size))) # compute end points of line end_points = np.zeros(brush_mask.shape,dtype=bool) first_point = i_js[0] last_point = i_js[-1] first_point_x = min(first_point[0] - bbox[0],brush_mask.shape[1]-1) first_point_y = min(first_point[1] - bbox[2], brush_mask.shape[0]-1) last_point_x = min(last_point[0] - bbox[0], brush_mask.shape[1]-1) last_point_y = min(last_point[1] - bbox[2], brush_mask.shape[0]-1) end_points[first_point_y, first_point_x] = True end_points[last_point_y, last_point_x] = True end_points = mh.morph.dilate(end_points, np.ones((2*brush_size, 2*brush_size))) # compute seeds seed_mask = np.zeros(brush_mask.shape,dtype=bool) # seed_mask[outside_brush_mask & brush_mask] = True seed_mask[outside_brush_mask] = True seed_mask[frame] = True # seed_mask[corners] = False seed_mask[end_points] = False # seeds,n = mh.label(brush_boundary_mask) seeds,n = mh.label(seed_mask) print(n) # remove small regions sizes = mh.labeled.labeled_size(seeds) min_seed_size = 5 too_small = np.where(sizes < min_seed_size) seeds = mh.labeled.remove_regions(seeds, too_small).astype(np.uint8) # # run watershed # ws = mh.cwatershed(brush_image.max() - brush_image, seeds) mh.imsave(self.__tmp_end_points_tif, 50*end_points.astype(np.uint8)) ########################################### mh.imsave(self.__tmp_seeds_mask_tif, 50*seed_mask.astype(np.uint8)) mh.imsave(self.__tmp_seeds_tif, 50*seeds.astype(np.uint8)) mh.imsave(self.__tmp_ws_tif, 50*ws.astype(np.uint8)) lines_array = np.zeros(ws.shape,dtype=np.uint8) lines = [] print(label_id) # valid_labels = [label_id] # while label_id in self.__merge_table.values(): # label_id = self.__merge_table.values()[] # valid_labels.append(label_id) for y in range(ws.shape[0]-1): for x in range(ws.shape[1]-1): if ws[y,x] != ws[y,x+1] and self.lookup_label(seg_sub_tile[y,x]) == label_id: lines_array[y,x] = 1 lines.append([bbox[0]+x,bbox[2]+y]) if ws[y,x] != ws[y+1,x] and self.lookup_label(seg_sub_tile[y,x]) == label_id: lines_array[y,x] = 1 lines.append([bbox[0]+x,bbox[2]+y]) for y in range(1,ws.shape[0]): for x in range(1,ws.shape[1]): if ws[y,x] != ws[y,x-1] and self.lookup_label(seg_sub_tile[y,x]) == label_id: lines_array[y,x] = 1 lines.append([bbox[0]+x,bbox[2]+y]) if ws[y,x] != ws[y-1,x] and self.lookup_label(seg_sub_tile[y,x]) == label_id: lines_array[y,x] = 1 #lines_array[y-1,x] = 1 lines.append([bbox[0]+x,bbox[2]+y]) mh.imsave(self.__tmp_lines_tif, 50*lines_array.astype(np.uint8)) ############################### output = {} output['name'] = 'SPLITRESULT' output['origin'] = input['origin'] output['value'] = lines # print output self.__websocket.send(json.dumps(output))
#Filter based on luminescence and chromatic channels imageY_S = imageY > 80 imageCr_S1 = imageCr > 135 imageCr_S2 = imageCr < 180 imageCr_S = imageCr_S1 & imageCr_S2 imageCb_S1 = imageCb > 85 imageCb_S2 = imageCb < 135 imageCb_S = imageCb_S1 & imageCb_S2 #Boolean matrix of the skin possibilities imageBWTemp = imageY_S & imageCr_S imageBW = imageBWTemp & imageCb_S #For debugging purposes #pylab.imshow(imageBW) #pylab.gray() #pylab.show() imageBWFilt = mh.gaussian_filter(imageBW,8) imageBWFilt = np.round(imageBWFilt*255) imageBWFiltInt = imageBWFilt.astype(np.uint8) #imageBWFiltInt = imageBWFiltInt*255 T = mh.thresholding.otsu(imageBWFiltInt) imageBWThresh = imageBWFiltInt > T #For debugging purposes pylab.imshow(imageBWThresh) pylab.gray() pylab.show()
# This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License from matplotlib import pyplot as plt import numpy as np import mahotas as mh image = mh.imread('../1400OS_10_01.jpeg') image = mh.colors.rgb2gray(image) im8 = mh.gaussian_filter(image, 8) im16 = mh.gaussian_filter(image, 16) im32 = mh.gaussian_filter(image, 32) h, w = im8.shape canvas = np.ones((h, 3 * w + 256), np.uint8) canvas *= 255 canvas[:, :w] = im8 canvas[:, w + 128:2 * w + 128] = im16 canvas[:, -w:] = im32 mh.imsave('../1400OS_10_05+.jpg', canvas[:, ::2]) im32 = mh.stretch(im32) ot32 = mh.otsu(im32) mh.imsave('../1400OS_10_06+.jpg', (im32 > ot32).astype(np.uint8) * 255)
import uuid # Loads both nuclear (DAPI) and cytoplasm (SE) images filenames = list(glob.glob('./new cellline/original images/*ch3*.tif')) for idx, imageNumber in enumerate(range(len(filenames))): #print filenamesSE[imageNumber] #if not filenamesSE[imageNumber] == './cell images/r05c05f65p01-ch2sk1fk1fl1.tiff': # continue # obtains image data image = skimage.io.imread(filenames[imageNumber]) # applys gaussina filter imagef = mh.gaussian_filter(image, 15) # finds threshold T = mh.thresholding.otsu(np.uint16(imagef)) imaget = imagef > T + 100 # Finds seeds on the nuclear image rmax = mh.regmax(imagef) pylab.imshow(rmax) rmax[np.logical_not(imaget)] = 0 # Watershed on the cytoplasm image seeds, nr_nuclei = mh.label(rmax) # nuclei count imagew = mh.cwatershed(-imagef, seeds) # Remove areas that aren't nuclei imagen = np.logical_not(imaget)
import numpy as np import pylab import mahotas as mh dna = mh.imread('playingcards2.jpg') dnaf = mh.gaussian_filter(dna, 1) dnaf = (dnaf.astype(np.uint8)) T = mh.otsu(dnaf) pylab.imshow(dnaf > T) pylab.show()
# -*- coding: utf-8 -*- """ Created on Fri Mar 24 14:23:01 2017 @author: rezaandriyunanto """ import numpy as np import pylab import mahotas as mh dna = mh.imread('sampledataset.jpg') pylab.imshow(dna) pylab.gray() pylab.show() #print dna.shape #print dna.dtype #print dna.max() #print dna.min() dnaf = mh.gaussian_filter(dna, 16) rmax = mh.regmax(dnaf) pylab.imshow(mh.overlay(dna, rmax))
def test_gaussian_small_sigma(): im = np.arange(128*4).reshape((16,-1)) mh.gaussian_filter(im, .01)
import scipy.ndimage as ndimage import scipy.misc as misc import scipy as mdimage import matplotlib.pylab as pyl import mahotas as mh # Circles # Read and show image circles = misc.imread('circles.png') pyl.imshow(circles) pyl.show() #Threshold T = mh.otsu(circles) circlesTh = (circles > T) circlesF = mh.gaussian_filter(circles, 33) circlesRegmax = mh.regmax(circlesF) labels, near = mh.label(circlesRegmax) pyl.imshow(mh.overlay(circles, circlesRegmax)) pyl.show() #Count circles km, circlesCnt = mh.label(circlesRegmax) print circlesCnt #Find center points centerMass = mh.center_of_mass(circles, labels)[1:] print centerMass #Objects objects = mh.imread('objects.png')
def test_gaussian_order(): im = np.arange(64*64).reshape((64,64)) for order in (1,2,3): g_mat = mahotas.gaussian_filter(im, 2., order=order)
## (TODO) Loop over each image in a directory ## (TODO) Load both nuclear (DAPI) and cytoplasm (SE) images ## (TODO) Find seeds on the nuclear image ## (TODO) Watershed on the cytoplasm image dna = mh.imread('dna.jpeg') # convert from memory to disk array dna = dna.squeeze() # change image array from 3d to 2d pylab.gray() # convert to gray scale pylab.imshow(dna) #pylab.show() # print image T = mh.thresholding.otsu(dna) # calculate a threshold value # apply a gaussian filter that smoothen the image dnaf = mh.gaussian_filter(dna, 8) dnat = dnaf > T # do threshold #labelling thereshold image labeled, nr_objects = mh.label(dnat) #print nr_objects # output number of objects #pylab.imshow(labeled) #pylab.jet() # makes image colourful # Watershed dnaf = mh.gaussian_filter(dna, 28) rmax = mh.regmax(dnaf) pylab.imshow(mh.overlay( dna, rmax)) # print dna and rmax (with second channel in red) #pylab.show() # seeds only show when image is zoomed in dist = mh.distance(dnat)
def filterImage(self,image,sd): if self.params['dirtyFilter']: self.params['filteredImage'] = mh.gaussian_filter(image,sd) self.params['dirtyFilter'] = 0 return self.params['filteredImage']
def main(image, filter_name, filter_size, plot=False): '''Smoothes (blurs) `image`. Parameters ---------- image: numpy.ndarray grayscale image that should be smoothed filter_name: str name of the filter kernel that should be applied (options: ``{"avarage", "gaussian", "median", "bilateral"}``) filter_size: int size of the kernel plot: bool, optional whether a plot should be generated (default: ``False``) Returns ------- jtmodules.smooth.Output[Union[numpy.ndarray, str]] Raises ------ ValueError when `filter_name` is not ``"avarage"``, ``"gaussian"``, ``"median"`` or ``"bilateral"`` ''' se = np.ones((filter_size, filter_size)) if filter_name == 'average': logger.info('apply "average" filter') smoothed_image = mh.mean_filter(image, se) elif filter_name == 'gaussian': logger.info('apply "gaussian" filter') smoothed_image = mh.gaussian_filter(image, filter_size) elif filter_name == 'median': logger.info('apply "median" filter') smoothed_image = mh.median_filter(image, se) elif filter_name == 'bilateral': smoothed_image = cv2.bilateralFilter(image.astype(np.float32), d=0, sigmaColor=filter_size, sigmaSpace=filter_size).astype( image.dtype) else: raise ValueError( 'Arugment "filter_name" can be one of the following:\n' '"average", "gaussian", "median" or "bilateral"') smoothed_image = smoothed_image.astype(image.dtype) if plot: logger.info('create plot') from jtlib import plotting clip_value = np.percentile(image, 99.99) data = [ plotting.create_intensity_image_plot(image, 'ul', clip=True, clip_value=clip_value), plotting.create_intensity_image_plot(smoothed_image, 'ur', clip=True, clip_value=clip_value), ] figure = plotting.create_figure( data, title='Smoothed with "{0}" filter (kernel size: {1})'.format( filter_name, filter_size)) else: figure = str() return Output(smoothed_image, figure)