def xor_rows_then_compare(grid, alt): if(len(grid) == 2): return 0 grid = copy.deepcopy(grid) grid[2].append(alt) top = reduce(lambda a, b: a^b, grid[0]) bot = reduce(lambda a, b: a^b, grid[2]) a_top = reduce(lambda a, b: a&b, grid[0], top) a_bot = reduce(lambda a, b: a&b, grid[2], bot) top_xor = pymorph.open(top^a_top) bot_xor = pymorph.open(bot^a_bot) return similarity(top_xor, bot_xor)
def xor_rows_then_compare(grid, alt): if (len(grid) == 2): return 0 grid = copy.deepcopy(grid) grid[2].append(alt) top = reduce(lambda a, b: a ^ b, grid[0]) bot = reduce(lambda a, b: a ^ b, grid[2]) a_top = reduce(lambda a, b: a & b, grid[0], top) a_bot = reduce(lambda a, b: a & b, grid[2], bot) top_xor = pymorph.open(top ^ a_top) bot_xor = pymorph.open(bot ^ a_bot) return similarity(top_xor, bot_xor)
def test_open(): img = np.array(pyplot.imread(path.join(_basedir, "img1.png")), dtype=bool) ref = np.array(pyplot.imread(path.join(_basedir, "b.png")), dtype=bool) expected = np.array(pyplot.imread(path.join(_basedir, "expected.png")), dtype=bool) se = pymorph.img2se(ref) res = pymorph.open(img, se) assert np.all(img[85:99, 280:289] == ref) assert np.all(res == expected)
def LowResSegmentation(image): """Perform a simple threshold after DoG filtering""" noBack = RemoveModalBackground(image) # print "from Segmeta noBack:",noBack.min(),noBack.mean() blurLowRes = nd.filters.gaussian_filter(noBack, 13) blurHiRes = nd.filters.gaussian_filter(noBack, 1) midPass = pymorph.subm(blurHiRes, 0.70 * blurLowRes) bin = midPass > 1.5 * midPass.mean() binLowRes = pymorph.open(bin, pymorph.sedisk(4)) return binLowRes
def LowResSegmentation(image): '''Perform a simple threshold after DoG filtering''' noBack=RemoveModalBackground(image) #print "from Segmeta noBack:",noBack.min(),noBack.mean() blurLowRes=nd.filters.gaussian_filter(noBack,13) blurHiRes=nd.filters.gaussian_filter(noBack,1) midPass=pymorph.subm(blurHiRes,0.70*blurLowRes) bin=(midPass>1.5*midPass.mean()) binLowRes=pymorph.open(bin,pymorph.sedisk(4)) return binLowRes
def test_open(): img = np.array(pyplot.imread(path.join(_basedir, 'img1.png')), dtype=bool) ref = np.array(pyplot.imread(path.join(_basedir, 'b.png')), dtype=bool) expected = np.array(pyplot.imread(path.join(_basedir, 'expected.png')), dtype=bool) se = pymorph.img2se(ref) res = pymorph.open(img, se) assert np.all(img[85:99, 280:289] == ref) assert np.all(res == expected)
def test_opentransf(): f = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0]], bool) ot = pymorph.opentransf(f, 'city-block') for y in xrange(ot.shape[0]): for x in xrange(ot.shape[1]): r = ot[y, x] t = f.copy() for k in xrange(1, r + 1): assert t[y, x] t = pymorph.open(f, pymorph.sedisk(k, 2, 'city-block')) assert not t[y, x]
def GradBasedSegmentation(im): blur=nd.gaussian_filter(im, 16) rmax = pymorph.regmax(blur) T = mahotas.thresholding.otsu(blur) bImg0=im>T #bImg01=nd.binary_closing(bImg0,iterations=2) bImg01=pymorph.close(bImg0, pymorph.sedisk(3)) bImg=pymorph.open(bImg01, pymorph.sedisk(4)) #bImg=nd.binary_opening(bImg01,iterations=3) b=pymorph.edgeoff(bImg) d=distanceTranform(b) seeds,nr_nuclei = nd.label(rmax) lab=mahotas.cwatershed(d,seeds) return lab
def GradBasedSegmentation(im): blur = nd.gaussian_filter(im, 16) rmax = pymorph.regmax(blur) T = mahotas.thresholding.otsu(blur) bImg0 = im > T # bImg01=nd.binary_closing(bImg0,iterations=2) bImg01 = pymorph.close(bImg0, pymorph.sedisk(3)) bImg = pymorph.open(bImg01, pymorph.sedisk(4)) # bImg=nd.binary_opening(bImg01,iterations=3) b = pymorph.edgeoff(bImg) d = distanceTranform(b) seeds, nr_nuclei = nd.label(rmax) lab = mahotas.cwatershed(d, seeds) return lab
def test_opentransf(): f = np.array([ [0,0,0,0,0,0,0,0], [0,0,1,1,1,1,0,0], [0,1,0,1,1,1,0,0], [0,0,1,1,1,1,0,0], [1,1,0,0,0,0,0,0]], bool) ot = pymorph.opentransf( f, 'city-block') for y in xrange(ot.shape[0]): for x in xrange(ot.shape[1]): r = ot[y,x] t = f.copy() for k in xrange(1, r+1): assert t[y,x] t = pymorph.open(f, pymorph.sedisk(k, 2, 'city-block')) assert not t[y,x]
def _getBlobs(im, minsize=10, opendisk=0): """ Find blobs in an image. :param im: input image :type im: numpy array :param minsize: minimal size of detected blobs :type minsize: int :param opendisk: disk size for opening operation (ommitted when opendisk <= 0) :type opendisk: int :return: identifiers for areas with blobs > minsize and labeled image (lac,lab) """ if opendisk > 0: im = m.open(im.astype(np.int), m.sedisk(opendisk)) n = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) lab, nr = labeled.label(im, n) sizes = np.bincount(np.reshape(lab, (lab.shape[0] * lab.shape[1]))) lac = np.nonzero(sizes > minsize)[0] return lac, lab
def region_prop(fig, subfig): # Inspired by: # http://stackoverflow.com/a/9059648/621449 c = subfig # set up the 'FilledImage' bit of regionprops. FilledImage = np.zeros(fig.shape[0:2]).astype('uint8') # set up the 'ConvexImage' bit of regionprops. ConvexImage = np.zeros(fig.shape[0:2]).astype('uint8') # calculate some things useful later: m = cv2.moments(c) # ** regionprops ** Area = m['m00'] Perimeter = cv2.arcLength(c,True) # bounding box: x,y,width,height BoundingBox = cv2.boundingRect(c) # centroid = m10/m00, m01/m00 (x,y) Centroid = ( m['m10']/m['m00'],m['m01']/m['m00'] ) # EquivDiameter: diameter of circle with same area as region EquivDiameter = np.sqrt(4*Area/np.pi) # Extent: ratio of area of region to area of bounding box Extent = Area/(BoundingBox[2]*BoundingBox[3]) # FilledImage: draw the region on in white cv2.drawContours( FilledImage, [c], 0, color=255, thickness=-1 ) # calculate indices of that region.. regionMask = (FilledImage==255) # FilledArea: number of pixels filled in FilledImage FilledArea = np.sum(regionMask) # PixelIdxList : indices of region. # (np.array of xvals, np.array of yvals) PixelIdxList = regionMask.nonzero() # CONVEX HULL stuff # convex hull vertices ConvexHull = cv2.convexHull(c) ConvexArea = cv2.contourArea(ConvexHull) # Solidity := Area/ConvexArea Solidity = Area/ConvexArea # convexImage -- draw on ConvexImage cv2.drawContours( ConvexImage, [ConvexHull], -1, color=255, thickness=-1 ) # ELLIPSE - determine best-fitting ellipse. centre,axes,angle = cv2.fitEllipse(c) MAJ = np.argmax(axes) # this is MAJor axis, 1 or 0 MIN = 1-MAJ # 0 or 1, minor axis # Note: axes length is 2*radius in that dimension MajorAxisLength = axes[MAJ] MinorAxisLength = axes[MIN] Eccentricity = np.sqrt(1-(axes[MIN]/axes[MAJ])**2) Orientation = angle EllipseCentre = centre # x,y Test = FilledImage.astype('uint8') mf = cv2.moments(Test) CentroidFilled = ( mf['m10']/mf['m00'],mf['m01']/mf['m00'] ) # # ** if an image is supplied with the fig: # # Max/Min Intensity (only meaningful for a one-channel img..) # MaxIntensity = np.max(img[regionMask]) # MinIntensity = np.min(img[regionMask]) # # Mean Intensity # MeanIntensity = np.mean(img[regionMask],axis=0) # # pixel value # PixelValues = img[regionMask] x0, y0, dx, dy = BoundingBox x1, y1 = x0 + dx, y0 + dy Image = fig[y0:y1, x0:x1] FilledImageFit = FilledImage[y0:y1, x0:x1] OImage = fig[y0-1:y1+1, x0-1:x1+1] NumPixels = Image.sum() Fillity = (NumPixels+0.0)/FilledArea crx, cry = (CentroidFilled[0]-x0, CentroidFilled[1]-y0) dxc = crx-(x1-x0)/2.0 dyc = cry-(y1-y0)/2.0 CentLength = math.sqrt(dxc*dxc + dyc*dyc) e = lambda fig: pymorph.erode(fig) d = lambda fig: pymorph.dilate(fig) o = lambda fig: pymorph.open(fig) c = lambda fig: pymorph.close(fig) a = lambda fun, n: reduce(lambda f1, f2: lambda x: f1(f2(x)), [fun]*n, lambda x: x) Thin = pymorph.thin(OImage) if num_holes(Image) >= 2: Inner = removeOuter(Thin) Inner = (a(d,7))(Inner>0) Outer = OImage > Inner ret = dict((k,v) for k, v in locals().iteritems() if k[0].isupper()) return ret
import cv2 import numpy import numpy as np import scipy import pylab as pl import pylab import pymorph from scipy import misc def s(fig): pl.imshow(fig); pl.gray(); pl.show() e = lambda fig: pymorph.erode(fig) d = lambda fig: pymorph.dilate(fig) o = lambda fig: pymorph.open(fig) c = lambda fig: pymorph.close(fig) a = lambda fun, n: reduce(lambda f1, f2: lambda x: f1(f2(x)), [fun]*n, lambda x: x) img= 255-cv2.imread('reps/2/2.png', cv2.CV_LOAD_IMAGE_GRAYSCALE) imgb = img > 128 BW=imgb # grab contours cs,_ = cv2.findContours( BW.astype('uint8'), mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE ) # set up the 'FilledImage' bit of regionprops. filledI = np.zeros(BW.shape[0:2]).astype('uint8') # set up the 'ConvexImage' bit of regionprops. convexI = np.zeros(BW.shape[0:2]).astype('uint8') # for each contour c in cs: # will demonstrate with cs[0] but you could use a loop.
def tentDetection_MM(strInputFile, maxTentArea, strOutputFile, strShape='box', iThresh_coeff=0): # five step to do this # 1. opening-determine the square structure element (6-60 m2/resolution) # 2. opening by reconstruction # 3. top-hat by reconstruction # 4. lower threshold # 5. double threshold import pymorph as pymm objImg = osgeo.gdal.Open(strInputFile, GA_ReadOnly) nRasterCount = objImg.RasterCount poDataset = objImg.ReadAsArray().astype(np.float) geotransform = objImg.GetGeoTransform() pixelWidth = np.fabs(geotransform[1]) pixelHeight = np.fabs(geotransform[5]) resolution = pixelWidth * pixelHeight # NoDataValue = objImg.GetRasterBand(1).GetNoDataValue() # gray scale image if (nRasterCount == 1): objnImg = pymm.to_int32(poDataset) # RGB image elif (nRasterCount == 3): objnImg = pymm.to_gray(poDataset) else: print 'it only supports gray-scale or RGB image' sys.exit(1) # determine the structure element iNum = int(np.sqrt(maxTentArea) / resolution) + 1 if (strShape == 'box'): objStructureElement = pymm.sebox(iNum) elif (strShape == 'cross'): objStructureElement = pymm.secross(iNum) else: objStructureElement = pymm.sedisk(iNum) # opening objOpen = pymm.open(objnImg, objStructureElement) # opening by reconstruction objOpenRec = pymm.openrec(objOpen, objStructureElement, objStructureElement) objtophat = pymm.openrecth(objnImg, objStructureElement, objStructureElement) # objtophat = pymm.subm(objnImg, objOpenRec) # objTent = pymm.threshad(objtophat, 0.25 * objnImg, 0.40 * objnImg) # y = mean + k*std (minValue, maxValue, meanValue, stdValue) = objImg.GetRasterBand(1).GetStatistics(0, 1) if (nRasterCount == 3): (minValue2, maxValue2, meanValue2, stdValue2) = objImg.GetRasterBand(2).GetStatistics(0, 1) (minValue3, maxValue3, meanValue3, stdValue3) = objImg.GetRasterBand(3).GetStatistics(0, 1) meanValue = 0.2989 * meanValue + 0.5870 * meanValue2 + 0.1140 * meanValue3 maxValue = 0.2989 * maxValue + 0.5870 * maxValue2 + 0.1140 * maxValue3 # meanValue = 438 # maxValue = 2047 threshad = meanValue + iThresh_coeff * stdValue objTent = pymm.threshad(objtophat, threshad, maxValue) data_list = [] data_list.append(objTent) WriteOutputImage(strOutputFile, 1, data_list, 0, 0, 0, strInputFile) '''
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)
def tentDetection_MM(strInputFile, maxTentArea, strOutputFile, strShape='box', iThresh_coeff=0): # five step to do this # 1. opening-determine the square structure element (6-60 m2/resolution) # 2. opening by reconstruction # 3. top-hat by reconstruction # 4. lower threshold # 5. double threshold import pymorph as pymm objImg = osgeo.gdal.Open(strInputFile, GA_ReadOnly) nRasterCount = objImg.RasterCount poDataset = objImg.ReadAsArray().astype(np.float) geotransform = objImg.GetGeoTransform() pixelWidth = np.fabs(geotransform[1]) pixelHeight = np.fabs(geotransform[5]) resolution = pixelWidth * pixelHeight # NoDataValue = objImg.GetRasterBand(1).GetNoDataValue() # gray scale image if (nRasterCount == 1): objnImg = pymm.to_int32(poDataset) # RGB image elif(nRasterCount == 3): objnImg = pymm.to_gray(poDataset) else: print 'it only supports gray-scale or RGB image' sys.exit(1) # determine the structure element iNum = int(np.sqrt(maxTentArea) / resolution) + 1 if (strShape == 'box'): objStructureElement = pymm.sebox(iNum) elif (strShape == 'cross'): objStructureElement = pymm.secross(iNum) else: objStructureElement = pymm.sedisk(iNum) # opening objOpen = pymm.open(objnImg, objStructureElement) # opening by reconstruction objOpenRec = pymm.openrec(objOpen, objStructureElement, objStructureElement) objtophat = pymm.openrecth(objnImg, objStructureElement, objStructureElement) # objtophat = pymm.subm(objnImg, objOpenRec) # objTent = pymm.threshad(objtophat, 0.25 * objnImg, 0.40 * objnImg) # y = mean + k*std (minValue, maxValue, meanValue, stdValue) = objImg.GetRasterBand(1).GetStatistics(0, 1) if (nRasterCount == 3): (minValue2, maxValue2, meanValue2, stdValue2) = objImg.GetRasterBand(2).GetStatistics(0, 1) (minValue3, maxValue3, meanValue3, stdValue3) = objImg.GetRasterBand(3).GetStatistics(0, 1) meanValue = 0.2989 * meanValue + 0.5870 * meanValue2 + 0.1140 * meanValue3 maxValue = 0.2989 * maxValue + 0.5870 * maxValue2 + 0.1140 * maxValue3 # meanValue = 438 # maxValue = 2047 threshad = meanValue + iThresh_coeff * stdValue objTent = pymm.threshad(objtophat, threshad, maxValue) data_list = [] data_list.append(objTent) WriteOutputImage(strOutputFile, 1, data_list, 0, 0, 0, strInputFile) '''
import scipy import pylab as pl import pylab import pymorph from scipy import misc def s(fig): pl.imshow(fig) pl.gray() pl.show() e = lambda fig: pymorph.erode(fig) d = lambda fig: pymorph.dilate(fig) o = lambda fig: pymorph.open(fig) c = lambda fig: pymorph.close(fig) a = lambda fun, n: reduce(lambda f1, f2: lambda x: f1(f2(x)), [fun] * n, lambda x: x) img = 255 - cv2.imread('reps/2/2.png', cv2.CV_LOAD_IMAGE_GRAYSCALE) imgb = img > 128 BW = imgb # grab contours cs, _ = cv2.findContours(BW.astype('uint8'), mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE) # set up the 'FilledImage' bit of regionprops. filledI = np.zeros(BW.shape[0:2]).astype('uint8') # set up the 'ConvexImage' bit of regionprops.
def alternative_solution(self, a, orientation='coronal', linethickness=10, outimg=False): ''' Paramenters ----------- a: original image in graylevel ''' H, W = a.shape if orientation == 'coronal': # UL = mm.limits(a)[1] # upper limit UL = 255 b = 1 - iacircle(a.shape, H / 3, (1.4 * H / 3, W / 2)) # Circle b = b[0:70, W / 2 - 80:W / 2 + 80] # Rectangle # if outimg: # b_ = 0 * a; b_[0:70, W / 2 - 80:W / 2 + 80] = UL * b # b_ only for presentation # b_[:, W / 2 - linethickness / 2:W / 2 + linethickness / 2] = UL # b_ only for presentation c = a + 0 c[:, W / 2 - linethickness / 2:W / 2 + linethickness / 2] = UL c[0:70, W / 2 - 80:W / 2 + 80] = (1 - b) * c[0:70, W / 2 - 80:W / 2 + 80] + b * UL c[0:40, W / 2 - 70:W / 2 + 70] = UL d = mm.open(c, mm.img2se(mm.binary(np.ones((20, 10))))) e = mm.close(d, mm.seline(5)) f = mm.close_holes(e) g = mm.subm(f, d) h = mm.close_holes(g) i = mm.areaopen(h, 1000) j1, j2 = iaotsu(i) # j = i > j1 ret, j = cv2.threshold(cv2.GaussianBlur(i, (7, 7), 0), j1, 255, cv2.THRESH_BINARY) k = mm.open(j, mm.seline(20, 90)) l = mm.areaopen(k, 1000) # m = mm.label(l) res = np.vstack( [np.hstack([c, d, e, f, g]), np.hstack([h, i, j, k, l])]) cv2.imshow('Result', res) cv2.waitKey(0) cv2.destroyAllWindows() ################################ # l_ = mm.blob(k,'AREA','IMAGE') # l = l_ == max(ravel(l_)) # m = mm.open(l, mm.sedisk(3)) # VERIFICAR O MELHOR ELEMENTO ESTRUTURANTE AQUI # n = mm.label(m) if outimg: if not os.path.isdir('outimg'): os.mkdir('outimg') def N(x): # y = uint8(ianormalize(x, (0, 255)) + 0.5) y = (ianormalize(x, (0, 255)) + 0.5).astype(np.uint8) return y adwrite('outimg/a.png', N(a)) adwrite('outimg/b.png', N(b_)) adwrite('outimg/c.png', N(c)) adwrite('outimg/d.png', N(d)) adwrite('outimg/e.png', N(e)) adwrite('outimg/f.png', N(f)) adwrite('outimg/g.png', N(g)) adwrite('outimg/h.png', N(h)) adwrite('outimg/i.png', N(i)) adwrite('outimg/j.png', N(j)) adwrite('outimg/k.png', N(k)) adwrite('outimg/l.png', N(l)) adwrite('outimg/m.png', N(m)) # adwrite('outimg/n.png', N(n)) return m else: b = mm.areaopen(a, 500) c = mm.close(b, mm.sebox(3)) d = mm.close_holes(c) e = mm.subm(d, c) f = mm.areaopen(e, 1000) # g = f > 5 ret, g = cv2.threshold(cv2.GaussianBlur(f, (5, 5), 0), 3, 255, cv2.THRESH_BINARY) # ret, g = cv2.threshold( # cv2.GaussianBlur(f, (7, 7), 0), # 5, 255, # cv2.THRESH_BINARY_INV) h = mm.asf(g, 'CO', mm.sedisk(5)) i = mm.close_holes(h) res = np.vstack( [np.hstack([a, b, c, d, e]), np.hstack([f, g, h, i, a])]) cv2.imshow('Result', res) cv2.waitKey(0) cv2.destroyAllWindows() if outimg: if not os.path.isdir('outimg'): os.mkdir('outimg') def N(x): y = (ianormalize(x, (0, 255)) + 0.5).astype(np.uint8) return y adwrite('outimg/a.png', N(a)) adwrite('outimg/b.png', N(b)) adwrite('outimg/c.png', N(c)) adwrite('outimg/d.png', N(d)) adwrite('outimg/e.png', N(e)) adwrite('outimg/f.png', N(f)) adwrite('outimg/g.png', N(g)) adwrite('outimg/h.png', N(h)) adwrite('outimg/i.png', N(i)) return i
glom_hed = rgb2hed(glom_rgb) #hed glom_h = glom_hed[:, :, 0] #hematoxylim glom_h = ia.ianormalize(glom_h) selem = disk(10) #elemento estruturante glom_h = np.array(glom_h) glom_h = 255 - uint8(glom_h) #Segmentation glom_by_reconsTopHat = morph.closerecth(glom_h,selem) #reconstrução morfológicas de fechamento global_thresh = threshold_otsu(glom_by_reconsTopHat) #Otsu glom_bin = glom_by_reconsTopHat > global_thresh + global_thresh*0.1 glom_bin = img_as_ubyte(glom_bin) selem = disk(3) glom_seg = morph.open(glom_bin, selem) glom_seg = morph.close(glom_seg, selem) #Fechamento final #Mostra as etapas fig, axes = plt.subplots(2, 3, figsize=(14, 10)) fig.suptitle('Preprocessing, segmentation') ax1, ax2, ax3, ax4, ax5, ax6 = axes.ravel() ax1.imshow(glom_rgb, vmin=0, vmax=255, cmap=plt.cm.gray); ax1.set_title("RGB") ax2.imshow(glom_hed, vmin=0, vmax=255, cmap=plt.cm.gray); ax2.set_title("HED") ax3.imshow(glom_h, cmap=plt.cm.gray); ax3.set_title("255 - H (Hematoxylin)") ax4.imshow(glom_by_reconsTopHat, vmin=0, vmax=255, cmap=plt.cm.gray); ax4.set_title("Closing-by-reconstruction top-hat") ax5.imshow(glom_bin, vmin=0, vmax=255, cmap=plt.cm.gray); ax5.set_title("Otsu Thresholding") ax6.imshow(glom_seg, vmin=0, vmax=255, cmap=plt.cm.gray); ax6.set_title("Opening") #------------------------------------------------------------------------------------------------ #Feature Extraction print "Feature Extraction:"