def processImage(im): imb = m.overlay(im) mahotas.imsave("before.png", imb) print imb.max() f = FingerProcess() b3 = f.process(im) imgout = m.overlay(im, b3) mahotas.imsave("lol.png", imgout)
def processImage(im): imb = m.overlay(im) mahotas.imsave("before.png",imb) print imb.max() f = FingerProcess() b3 = f.process(im) imgout = m.overlay(im,b3) mahotas.imsave("lol.png", imgout)
def plot(self, pylab, xmax=100, areaunit="micron"): """Helper routine for plotting in this task""" if not hasattr(self, "clusters"): self.clusterparticles() if not hasattr(self, "rdf"): self.radialdistribution() # Various stages of the image analysis are straightforward # 1 - filtered images # 2 - threshold with seeds # 3 - nanoparticle regions # 4 - centers of mass on to of original image # 5 - colored clusters of nanoparticles # The list figure_params contains parameter tuples to pass to imshow, # with the mandatory and optional parameters (in a dict) as elements figure_params = [ (self.filtered, dict()), (pymorph.overlay(self.threshold, self.seeds), dict()), ((self.nps % 20 + 5)*(self.nps>0), dict(cmap=pylab.cm.spectral)), (pymorph.overlay(self.img, self.regcom), dict()), ((self.clusters % 20 + 5)*(self.clusters>0), dict(cmap=pylab.cm.spectral)), ] for ip,params in enumerate(figure_params): pylab.figure(ip+1) pylab.imshow(params[0], **params[1]) pylab.xticks([]) pylab.yticks([]) # Now the RDF plot (zoomed in to the first few peaks) # Remember to scale everything by the pixel size # Add lines and labels at multiples of the first peak # Also add a larger portion of the RDF in an inset pylab.figure(len(figure_params)+1) ymax = 1.01*max(2.5,max(self.rdf)) rdfxunits = "nm"*hasattr(self,"ps") or "pixels" expconc = self.npconc*(areaunit=="micron") or self.npconc / 10.0**6 explabel = "experimental %.1f/micron$^2$"*(areaunit=="micron") or "experiment (%.1f/nm$^2$)" pylab.plot(self.bins*self.ps, self.rdf, label=explabel %expconc) if hasattr(self, "rdfmodel"): pylab.plot(self.bins*self.ps, self.rdfmodel(self.bins*self.ps), label="hard sphere liquid model") for peak,label in [(1,"$d=%.1f\mathrm{nm}$" %self.rdfmax), (numpy.sqrt(3),"$\sqrt{3}$"), (2,"$2$"), (numpy.sqrt(7),"$\sqrt{7}$")]: x = peak*self.rdfmax pylab.axvline(x=x, ymin=0, ymax=ymax, linestyle='--', color='gray') pylab.text(x, ymax*1.02, label, fontsize=15, horizontalalignment="center") pylab.xlabel("distance [%s]" %rdfxunits) pylab.ylabel("g(r)") pylab.xlim([0, xmax]) pylab.ylim([0.0, ymax]) pylab.legend() pylab.grid() a = pylab.axes([0.60, 0.50, 0.25, 0.25], axisbg='y') pylab.plot(self.bins*self.ps, self.rdf) pylab.setp(a, xticks=map(int,[xmax/2.0,xmax,1.5*xmax]), yticks=[1.0]) pylab.xlim([0,2*xmax]) pylab.grid()
def overlay(img,regions): """ """ import pymorph; plt = pyplot; over_img = pymorph.overlay(img,regions) plt.imshow(over_img) return plt
def save_wormviz_image(vizdir,imname,Image,red,green=None,blue=None, magneto=None,yellow=None,cyan=None): ''' Save an image with color overlays. vizdir: directory where image will be saved imname: name of saved image, include ".jpg" Image: The base grayscale image. red,green,blue,magneto,yellow,cyan: binary arrays that should be overlayed. Pass "None" to select a color out of order. e.g., with one binary array only that should be blue, output = save_wormviz_image(vizdir,imname,Image,None,None,BlueArr) ''' im = pymorph.overlay(Image,red,green,blue,magneto,yellow,cyan) scipy.misc.imsave(os.path.join(vizdir,imname) ,im)
def next(self, rgb): """ Process the next file and return the results. """ def blackout_date_regions(image, blackout_rects): """ Black out specified regions. """ for rect in blackout_rects: image[rect[1]:rect[3], rect[0]:rect[2]] = 0 # Do bright object detection. blackout_date_regions(rgb, night.BLACKOUT_RECTS) steps = night.bright_object_detection(rgb) # Return results (channels are reversed RGB = BGR). label_img = pymorph.overlay(steps['luminance'].astype('uint8'), blue=steps['detect_dilate']) return steps['bright_blob_count'], label_img
def process(self, im): # single pixel restructure element elem = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) print "starting img process.. binarizing" b1 = im > 205 # binarize print "removing single pixels" # remove single pixels singpix = mahotas.morph.hitmiss(b1, elem) b1 = (b1 - singpix) > 0 print "closing holes" b1 = m.close_holes(b1) print "thinning" # b2 = m.thin(b1) #thin b2 = self.shitthin(b1) # thin print "pruning" b3 = m.thin(b2, m.endpoints("homotopic"), 8) # remove single pixels singpix = mahotas.morph.hitmiss(b3, elem) b3 = b3 - singpix b3 = b3 > 0 struct = np.ndarray((4, 3, 3), dtype=np.uint8) struct[0, :, :] = [[1, 2, 1], [0, 1, 0], [0, 1, 0]] for i in range(1, 4): print "gen %i structure.." % (i) struct[i, :, :] = np.rot90(struct[0], i) # struct = struct == 1 print "using struct for branch summing:" print struct b4 = np.zeros((301, 398), dtype=bool) for i in range(0, 4): b4 = b4 | mahotas.morph.hitmiss(b3, struct[i]) b4 = b4 > 0 imgout = m.overlay(b1, b2, b4) mahotas.imsave("thresh.png", imgout) return b4
def process(self, im): #single pixel restructure element elem = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) print "starting img process.. binarizing" b1 = im > 205 #binarize print "removing single pixels" #remove single pixels singpix = mahotas.morph.hitmiss(b1, elem) b1 = (b1 - singpix) > 0 print "closing holes" b1 = m.close_holes(b1) print "thinning" #b2 = m.thin(b1) #thin b2 = self.shitthin(b1) #thin print "pruning" b3 = m.thin(b2, m.endpoints('homotopic'), 8) #remove single pixels singpix = mahotas.morph.hitmiss(b3, elem) b3 = b3 - singpix b3 = b3 > 0 struct = np.ndarray((4, 3, 3), dtype=np.uint8) struct[0, :, :] = [[1, 2, 1], [0, 1, 0], [0, 1, 0]] for i in range(1, 4): print "gen %i structure.." % (i) struct[i, :, :] = np.rot90(struct[0], i) #struct = struct == 1 print "using struct for branch summing:" print struct b4 = np.zeros((301, 398), dtype=bool) for i in range(0, 4): b4 = b4 | mahotas.morph.hitmiss(b3, struct[i]) b4 = b4 > 0 imgout = m.overlay(b1, b2, b4) mahotas.imsave("thresh.png", imgout) return b4
import copy import skimage.filter as skif import skimage.morphology as morph import matplotlib.pyplot as mpl import skimage.feature as feature import pylab import mahotas import pymorph from skimage.filter import canny ### Circles ### raw_circle = misc.imread('circles.png') img_circle = ndimage.gaussian_filter(raw_circle, 15) rmax_circle = pymorph.regmax(img_circle) pylab.imshow(pymorph.overlay(img_circle, rmax_circle)) pylab.show() seeds_circle, nr_circles = ndimage.label(rmax_circle) print "Number of objects: " + str(nr_circles) centers_circles = ndimage.center_of_mass(rmax_circle, seeds_circle, range(1, nr_circles + 1, 1)) print "Centers of gravity: " + str(centers_circles) ### Objects ### raw_objects = misc.imread('objects.png') img_objects = ndimage.gaussian_filter(raw_objects, 3) thres_objects = img_objects > img_objects.mean() pylab.imshow(thres_objects) pylab.show() # regmax is resulting in an error. Looks like this is working
def writeimg(img, name): pass else: def savejet(img, name): img = (img - img.min()) / float(img.ptp()) * 255 img = img.astype(np.uint8) readmagick.writeimg((cm.jet(img)[:, :, :3] * 255).astype(np.uint8), name) writeimg = readmagick.writeimg dnaf = ndimage.gaussian_filter(dna, 8) rmax = pymorph.regmax(dnaf) pylab.imshow(pymorph.overlay(dna, rmax)) pylab.show() writeimg(pymorph.overlay(dna, rmax), 'dnaf-rmax-overlay.jpeg') savejet(dnaf, 'dnaf-8.jpeg') dnaf = ndimage.gaussian_filter(dna, 16) rmax = pymorph.regmax(dnaf) pylab.imshow(pymorph.overlay(dna, rmax)) pylab.show() writeimg(pymorph.overlay(dna, rmax), 'dnaf-16-rmax-overlay.jpeg') seeds, nr_nuclei = ndimage.label(rmax) print nr_nuclei T = pit.thresholding.otsu(dnaf) dist = ndimage.distance_transform_edt(dnaf > T)
def main(infile): img = mahotas.imread(infile) infile = os.path.splitext( os.path.basename(infile))[0] blue_component = img[:,:,B] pylab.gray() k = 3 f = ndimage.gaussian_filter(blue_component, 12) if DEBUG: print 'Procesando imagen %s usando canal azul' % (infile) mahotas.imsave('00%s-input.jpg' % infile, f) clustered = segment_kmeans(f, k) clustered[clustered == k-1] = 0 mask = ndimage.binary_fill_holes(clustered) if DEBUG: print 'Segmentacion inicial k-means con k=%d' % k mahotas.imsave('01kmeans1%s.jpg' % infile, mask) masked = f * mask if DEBUG: mahotas.imsave('02masked%s.jpg' % infile, masked) k = 4 clustered2 = segment_kmeans(masked, k) if DEBUG: print 'Resegmentacion k-means con k=%d' % k mahotas.imsave('03kmeans2%s.jpg' % infile, clustered2) clustered2[(clustered2 != k-2)] = 0 clustered2[(clustered2 == k-2)] = 1 if DEBUG: mahotas.imsave('04kmeans2binary%s.jpg' % infile, clustered2) clustered2 = ndimage.binary_fill_holes(clustered2) labeled, _ = mahotas.label(mask) if DEBUG: print 'Etiquetando imagen segmentacion inicial k-means' mahotas.imsave('05kmeans2noholes%s.jpg' % infile, clustered2) mahotas.imsave('06kmeans2labeled%s.jpg' % infile, labeled) while True: min_max = raw_input('label1 min,max? ') try: min_max = min_max.strip().split(',') min_ = int(min_max[0]) max_ = int(min_max[1]) except: break labeled1 = remove_by_size(labeled, min_, max_) mahotas.imsave('07labeled1f%d,%d%s.jpg' % (min_, max_, infile), labeled1) labeled, _ = mahotas.label(clustered2) labeled2 = remove_by_size(labeled, 1600, 23000) if DEBUG: print 'Etiquetando imagen re-segmentacion k-means' mahotas.imsave('08labeled2f%s.jpg' % infile, labeled) mahotas.imsave('09labeled2f%s.jpg' % infile, labeled2) combined = labeled1 + labeled2 labeled_to_binary(combined) if DEBUG: mahotas.imsave('10combined%s.jpg' % infile, combined) combined = ndimage.binary_fill_holes(combined) if DEBUG: mahotas.imsave('11combined_noholes%s.jpg' % infile, combined) borders = mahotas.labeled.borders(mahotas.label(combined)[0]) cells = f * combined cells[cells == 0] = 255 if DEBUG: mahotas.imsave('12maskedcellsw%s.jpg' % infile, cells) rmin = mahotas.regmin(cells) seeds, nr_nuclei = mahotas.label(rmin) if DEBUG: mahotas.imsave( '13gscale-final%s.jpg' % infile, pymorph.overlay(blue_component, rmin, borders) ) img2 = np.copy(img) img2[borders] = [0,0,0] img2[rmin] = [5,250,42] mahotas.imsave('14%s-outputcells.jpg' % (infile), img2) #watershed gradient = ndimage.morphology.morphological_gradient(combined, size=(3,3)) gradient = gradient.astype(np.uint8) if DEBUG: print 'Watershed' mahotas.imsave('15%s-gradient.jpg' % infile, gradient) wshed, lines = mahotas.cwatershed(gradient, seeds, return_lines=True) pylab.jet() if DEBUG: mahotas.imsave('16wshed.jpg', wshed) ncells = len(np.unique(wshed)) - 1 print '%d cells.' % ncells borders = mahotas.labeled.borders(wshed) img[borders] = [0,0,0] img[rmin] = [5,250,42] mahotas.imsave('17%s-output-%dcells.jpg' % (infile, ncells), img)
io.imshow(thr, cmap=plt.cm.gray) plt.show() dis = nd.distance_transform_edt(thr).astype(np.float32) # denoise the EDM blur = nd.gaussian_filter(dis, sigma=[filtSize, filtSize]) if bShowIntermed: print(blur.shape) print(blur.dtype) plt.imshow(-blur, cmap=plt.cm.jet, interpolation='nearest') plt.show() rmax = fea.peak_local_max(blur, indices=False, footprint=np.ones((3, 3))) if bShowIntermed: plt.imshow(pm.overlay(im, rmax)) plt.show() mrk = nd.label(rmax)[0] lab = mor.watershed(-blur, mrk, mask=thr) if bShowIntermed: io.imshow(lab, cmap=plt.cm.spectral) plt.show() props = mea.regionprops(lab, intensity_image=im, cache=True) if (bVerbose): print("") l = len(props) f = open(fOut, 'w')
io.imshow(thr, cmap=plt.cm.gray) plt.show() dis = nd.distance_transform_edt(thr).astype(np.float32) # denoise the EDM blur = nd.gaussian_filter(dis, sigma=[filtSize, filtSize]) if bShowIntermed: print(blur.shape) print(blur.dtype) plt.imshow(-blur, cmap=plt.cm.jet, interpolation="nearest") plt.show() rmax = fea.peak_local_max(blur, indices=False, footprint=np.ones((3, 3))) if bShowIntermed: plt.imshow(pm.overlay(im, rmax)) plt.show() mrk = nd.label(rmax)[0] lab = mor.watershed(-blur, mrk, mask=thr) if bShowIntermed: io.imshow(lab, cmap=plt.cm.spectral) plt.show() props = mea.regionprops(lab, intensity_image=im, cache=True) if bVerbose: print("") l = len(props)
# # Predictions with regmax method blur_imgH = scipy.ndimage.gaussian_filter(mito_prob, 16) mito_pred3 = blur_imgH<90 blur_imgH = blur_imgH.astype(np.uint8) mito_pred3 = mahotas.erode(mito_pred3, disc) mito_pred3 = mito_pred3.astype(np.uint8) # labeled, nr_objects = scipy.ndimage.label(mito_pred3) # print nr_objects # labeled = labeled.astype(np.uint8) rmax = pymorph.regmax(blur_imgH) pylab.imshow(pymorph.overlay(mito_prob, rmax)) pylab.gray() pylab.show() seeds,nr_nuclei = scipy.ndimage.label(rmax) print nr_nuclei pylab.imshow(mito_pred3) pylab.show() dist = scipy.ndimage.distance_transform_edt(mito_pred3) dist = dist.max() - dist dist-=dist.min() dist = dist/float(dist.ptp())*255 dist = dist.astype(np.uint8) pylab.imshow(dist) pylab.gray() pylab.show() nuclei = pymorph.cwatershed(dist, seeds)
def test_overlay(): img = pylab.imread('pymorph/data/fabric.tif') assert pymorph.overlay(img, img == 255).shape == (img.shape + (3,))
def main(argv): now = datetime.datetime.now() # Need one command line argument. if len(argv) is not 2: print "Usage: {0} SERIES_FILE_PATH".format(argv[0]) raise Exception("Invalid command-line parameters.") # Extract command-line parameters. This is the name of one file in the # series. path, filename = os.path.split(argv[1]) file_name, file_ext = os.path.splitext(os.path.basename(filename)) series_name_end = file_name.rindex('_') series_name = file_name[:series_name_end] print "Processing image series {0} in path {1}.".format(series_name, path) files_in_path = os.listdir(path) series_pattern = series_name + '_[0-9]*' + file_ext print "Processing files matching pattern {0}.".format(series_pattern) series_suffixes = [int(os.path.splitext(fn)[0].split('_')[-1]) \ for fn in files_in_path \ if fnmatch.fnmatch(fn, series_pattern)] series_suffixes.sort() print "Found {0} files in image series {1}.".format(len(series_suffixes), series_name) label_img_path = "{}{:02d}{:02d}_{:02d}{:02d}{:02d}_{}_labeled".format( now.year, now.month, now.day, now.hour, now.minute, now.second, series_name) os.mkdir(label_img_path) # Process the files. bright_object_counts = [] for suffix in series_suffixes: series_filename = series_name + '_' + str(suffix) + file_ext print "Processing file {0}.".format(series_filename) image = ndimg.imread(os.path.join(path, series_filename)) # Black out specified regions. for rect in BLACKOUT_RECTS: image[rect[1]:rect[3], rect[0]:rect[2]] = 0 steps = bright_object_detection(image) bright_object_counts.append((steps['bright_blob_count'], steps['bright_pixel_count'])) # Save labeled file. label_img_filename = os.path.join(label_img_path, str(suffix) + file_ext) label_img = pymorph.overlay(steps['luminance'].astype('uint8'), steps['detect_dilate']) PIL.Image.fromarray(label_img).save(label_img_filename) # Compute exponential moving averages. blob_counts = [count[0] for count in bright_object_counts] blob_exp_avg = exponential_moving_average(blob_counts, 0.1) blob_exp_avg_norm = np.array(blob_exp_avg) / max(blob_exp_avg) pixel_counts = [count[1] for count in bright_object_counts] pixel_exp_avg = exponential_moving_average(pixel_counts, 0.1) pixel_exp_avg_norm = np.array(pixel_exp_avg) / max(pixel_exp_avg) # Make plots. p = plab.subplot('111') p.plot(blob_exp_avg_norm, 'b', label='blob_count') p.plot(pixel_exp_avg_norm, 'g', label='pixel_count') p.set_title("Normalized bright object count in {0} sequence." .format(series_name)) p.set_ylabel('normalized count') p.set_xlabel('frame index') p.legend(loc=4) # Save plots plot_filename = "{}{:02d}{:02d}_{:02d}{:02d}{:02d}_{}_results.png".format( now.year, now.month, now.day, now.hour, now.minute, now.second, series_name) plab.savefig(plot_filename) # Write results. resuts_filename = "{}{:02d}{:02d}_{:02d}{:02d}{:02d}_{}_results".format( now.year, now.month, now.day, now.hour, now.minute, now.second, series_name) results_file = os.open(resuts_filename, os.O_CREAT | os.O_WRONLY) os.write(results_file, "# List of result tuples (blob_count, pixel_count).\n") os.write(results_file, str(bright_object_counts)) os.close(results_file) return 0
import copy import skimage.filter as skif import skimage.morphology as morph import matplotlib.pyplot as mpl import skimage.feature as feature import pylab import mahotas import pymorph from skimage.filter import canny ### Circles ### raw_circle = misc.imread('circles.png') img_circle = ndimage.gaussian_filter(raw_circle, 15) rmax_circle = pymorph.regmax(img_circle) pylab.imshow(pymorph.overlay(img_circle, rmax_circle)) pylab.show() seeds_circle, nr_circles = ndimage.label(rmax_circle) print "Number of objects: " + str(nr_circles) centers_circles = ndimage.center_of_mass(rmax_circle, seeds_circle, range(1, nr_circles + 1, 1)) print "Centers of gravity: " + str(centers_circles) ### Objects ### raw_objects = misc.imread('objects.png') img_objects = ndimage.gaussian_filter(raw_objects, 3) thres_objects = img_objects > img_objects.mean() pylab.imshow(thres_objects) pylab.show() # regmax is resulting in an error. Looks like this is working # withoutt this function though.
TESTING = False if TESTING: def savejet(img, name): pass def writeimg(img, name): pass else: def savejet(img, name): img = (img - img.min())/float(img.ptp())*255 img = img.astype(np.uint8) readmagick.writeimg((cm.jet(img)[:,:,:3]*255).astype(np.uint8), name) writeimg = readmagick.writeimg dnaf = ndimage.gaussian_filter(dna, 8) rmax = pymorph.regmax(dnaf) pylab.imshow(pymorph.overlay(dna, rmax)) pylab.show() writeimg(pymorph.overlay(dna, rmax), 'dnaf-rmax-overlay.jpeg') savejet(dnaf, 'dnaf-8.jpeg') dnaf = ndimage.gaussian_filter(dna, 16) rmax = pymorph.regmax(dnaf) pylab.imshow(pymorph.overlay(dna, rmax)) pylab.show() writeimg(pymorph.overlay(dna, rmax), 'dnaf-16-rmax-overlay.jpeg') seeds,nr_nuclei = ndimage.label(rmax) print nr_nuclei T = pit.thresholding.otsu(dnaf)
import pymorph as m import mahotas from numpy import where, reshape image = mahotas.imread('B.png') # Load image b1 = image[:,:,0] < 100 # Make a binary image from the thresholded red channel b2 = m.erode(b1, m.sedisk(4)) # Erode to enhance contrast of the bridge b3 = m.open(b2,m.sedisk(4)) # Remove the bridge b4 = b2-b3 # Bridge plus small noise b5 = m.areaopen(b4,1000) # Remove small areas leaving only a thinned bridge b6 = m.dilate(b3)*b5 # Extend the non-bridge area slightly and get intersection with the bridge. #b6 is image of end of bridge, now find single points b7 = m.thin(b6, m.endpoints('homotopic')) # Narrow regions to single points. labelled = m.label(b7) # Label endpoints. x1, y1 = reshape(where(labelled == 1),(1,2))[0] x2, y2 = reshape(where(labelled == 2),(1,2))[0] outputimage = m.overlay(b1, m.dilate(b7,m.sedisk(5))) mahotas.imsave('output.png', outputimage)
############################################################################### # Three sigmas image and binary threshold. steps['maha_sq'] = (steps['diff_mean'] > 0) * steps['diff_mean_sq'] / \ steps['variance'] steps['thresh_maha'] = (steps['maha_sq'] > (NUM_STDDEV * NUM_STDDEV)) print "Bianry image from local maha:" plab.imshow(steps['thresh_maha'], cmap='gray') # <demo> stop # <demo> auto print "Detected light regions using maha with {0} "\ "standard deviations:".format(NUM_STDDEV) plab.imshow(pymorph.overlay(steps['luminance'].astype('uint8'), steps['thresh_maha'])) # <demo> stop # <demo> auto ############################################################################### # Integrate global illumination effects by taking a top percentage of # intensities from the detected light regions. steps['masked_regions_lum'] = steps['thresh_maha'] * steps['luminance'] steps['masked_regions_hist'] = pymorph.histogram(steps['masked_regions_lum']) steps['global_bright_thresh'] = int((len(steps['masked_regions_hist']) * \ (1.0 - GLOBAL_BRIGHT_PCT)) + 0.5) steps['thresh_global'] = steps['masked_regions_lum'] >= \ steps['global_bright_thresh'] print "Global filtered mask:"
#!/usr/bin/python import numpy as np import scipy import pylab import pymorph import mahotas from scipy import ndimage import sys dna = mahotas.imread(sys.argv[1]) gauss = int(sys.argv[2]) dnaf = ndimage.gaussian_filter(dna, gauss) rmax = pymorph.regmax(dnaf) T = mahotas.thresholding.otsu(dnaf) labeled,nr_objects = ndimage.label(dnaf > T) seeds,nr_nuclei = ndimage.label(rmax) print nr_nuclei pylab.imshow(pymorph.overlay(dna,rmax)) #pylab.jet() pylab.show()
for ele in range(0, 4): b = b | mahotas.morph.hitmiss(b, structleft[ele]) b = b | mahotas.morph.hitmiss(b, structright[ele]) print(np.all(lastFrame == b)) if np.all(lastFrame == b) == True: break lastFrame = np.copy(b).astype(bool) ct += 1 return lastFrame > 0 def kmeans(self, img, maxiter): X = img thresh = X.mean() for iter in range(maxiter): thresh = (X[X < thresh].mean() + X[X >= thresh].mean()) / 2.0 X[X < thresh] = 0 X[X >= thresh] = 255 return X == 255 if __name__ == "__main__": im = mahotas.imread("before.png") im = im[:, :, 0] f = FingerProcess() b4 = f.process(im) imgout = m.overlay(im, b4) mahotas.imsave("lol.png", imgout)
pylab.show() # Deal with merged/touching nuclei labeled,nr_objects = ndimage.label(dnaf > T) print nr_objects # prints 18 pylab.imshow(labeled) pylab.jet() # resets to jet from gray-scale pylab.show() ############ STEP TWO -- Segmenting Image/Finding seeds # Smooth image->find regional maxima->use maxima as seeds for watershed # First try: dnaf = ndimage.gaussian_filter(dna, 8) rmax = pymorph.regmax(dnaf) pylab.imshow(pymorph.overlay(dna, rmax)) # Overlay returns a color image with gray level component in first argument, second arg is red pylab.show() # Second try - Increase sigma: dnaf = ndimage.gaussian_filter(dna, 16) rmax = pymorph.regmax(dnaf) pylab.imshow(pymorph.overlay(dna, rmax)) seeds,nr_nuclei = ndimage.label(rmax) print nr_nuclei # prints 22 # Watershed to distance transform of threshold T = mahotas.thresholding.otsu(dnaf) dist = ndimage.distance_transform_edt(dnaf > T) dist = dist.max() - dist dist -= dist.min()
import readmagick import pymorph import mahotas dna = readmagick.readimg('dna-0.xcf[0]').max(2) dna2 = readmagick.readimg('dna-1.xcf[0]').max(2) borders = readmagick.readimg('dna-0.xcf[1]') borders = borders[:,:,0] > borders[:,:,1] for i in xrange(2): borders = mahotas.dilate(borders, np.ones((3,3))) readmagick.writeimg(pymorph.overlay(dna, borders), 'dna.png') readmagick.writeimg(pymorph.overlay(dna2, borders), 'dna2.png')
for ele in range(0, 4): b = b | mahotas.morph.hitmiss(b, structleft[ele]) b = b | mahotas.morph.hitmiss(b, structright[ele]) print (np.all(lastFrame == b)) if np.all(lastFrame == b) == True: break lastFrame = np.copy(b).astype(bool) ct += 1 return lastFrame > 0 def kmeans(self, img, maxiter): X = img thresh = X.mean() for iter in range(maxiter): thresh = (X[X < thresh].mean() + X[X >= thresh].mean()) / 2.0 X[X < thresh] = 0 X[X >= thresh] = 255 return X == 255 if __name__ == "__main__": im = mahotas.imread("before.png") im = im[:, :, 0] f = FingerProcess() b4 = f.process(im) imgout = m.overlay(im, b4) mahotas.imsave("lol.png", imgout)