Пример #1
0
 def findRegions(self, im):
     minsize = self.settings['minsize']
     maxsize = self.settings['maxsize']
     regions, image = libCVwrapper.FindRegions(im, minsize, maxsize, 0, 0,
                                               1, 1)
     coords = map(self.regionCenter, regions)
     self.setTargets(coords, 'Peak')
     return regions
	def findRegions(self):
		imshape = self.currentimagedata['image'].shape
		minsize = self.settings['min region area']
		maxsize = self.settings['max region area']
		velimit = self.settings['ve limit']
		regions,image = libCVwrapper.FindRegions(self.currentimagedata['image'], minsize, maxsize)
		self.regionarrays = []
		displaypoints = []
		for i,region in enumerate(regions):
			regionarray = region['regionBorder']
			self.logger.info('Region %d has %d points' % (i, regionarray.shape[1]))
			## reduce to 20 points
			regionarray = libCVwrapper.PolygonVE(regionarray, velimit)
			regionarray.transpose()
			self.regionarrays.append(regionarray)

			regiondisplaypoints = self.transpose_points(regionarray)
			displaypoints.extend(regiondisplaypoints)

		self.setTargets(displaypoints, 'Perimeter', block=False)
    def findRegions(self):
        imshape = self.mosaicimage.shape
        self.regionarrays = []
        self.regionellipses = []
        self.regionimage = numpy.zeros(imshape)
        maxsize = self.settings['max region area']
        minsize = self.settings['min region area']
        onesectionarea1 = self.settings['section area']
        sectionaxisratio = float(self.settings['section axis ratio'])
        maxsection = self.settings['max sections']
        displaysection = self.settings['section display']
        findsectionoption = self.settings['find section options']
        modifyarea = self.settings['adjust section area']

        newareasetting = False
        if self.oldonesectionarea1 == None or self.oldonesectionarea1 != self.settings[
                'section area'] or modifyarea < 0.01:
            newareasetting = True
        self.oldonesectionarea1 = onesectionarea1

        if findsectionoption == 'Sections Only':
            sectiononly = True
            limitbysection = False
        else:
            if findsectionoption == 'Limit by Sections':
                limitbysection = True
                sectiononly = False
            else:
                limitbysection = False
                sectiononly = False

        minsize /= 100.0
        maxsize /= 100.0
        onesectionarea = onesectionarea1 / 100.0
        modifyarea = modifyarea / 100.0

        tileshape = self.mosaic.tiles[0].image.shape
        tilearea = tileshape[0] * tileshape[1]
        mosaicarea = imshape[0] * imshape[1]
        areascale = self.mosaic.scale * self.mosaic.scale
        scale = areascale * tilearea / mosaicarea
        minsize = scale * minsize
        maxsize = scale * maxsize
        onesectionarea = scale * onesectionarea

        if findsectionoption == 'Regions from Centers':
            manualcenters = self.panel.getTargetPositions('region')
            if manualcenters:
                manualcenters = self.transpose_points(manualcenters)
            maxsizepixel = maxsize * mosaicarea
            self.regionarrays = self.regionsFromCenters(
                manualcenters, maxsizepixel)
            self.regionellipses = manualcenters
            return

        velimit = self.settings['ve limit']
        mint = self.settings['min threshold']
        maxt = self.settings['max threshold']
        axisratiolimit = self.settings['axis ratio']

        # make zero border
        pad = 2
        self.mosaicimage[:pad] = 0
        self.mosaicimage[-pad:] = 0
        self.mosaicimage[:, :pad] = 0
        self.mosaicimage[:, -pad:] = 0
        t00 = time.time()
        print "-------------"

        # get background stats
        background = numpy.where(self.mosaicimage > maxt, 1, 0)
        backgroundlabel, nlabels = nd.label(background)
        bkgrndmean = nd.mean(self.mosaicimage, labels=backgroundlabel)
        bkgrndstddev = nd.standard_deviation(self.mosaicimage,
                                             labels=backgroundlabel)
        t01 = time.time()
        print "---%5.1f-----background mean %f, stddev %f" % (
            (t01 - t00), bkgrndmean, bkgrndstddev)

        #refresh to setting if not auto adjust
        if self.onesectionarea == None or newareasetting:
            self.onesectionarea = onesectionarea

        tolerance = 0.5
        onesectionmin = self.onesectionarea * (1 - tolerance)
        multisections = self.onesectionarea * maxsection * (1 + tolerance)

        sectiondisplaypoints = []
        sectionarrays = []
        sectionellipses = []

        #               Find Section with simple thresholding and Label in scipy.ndimage for now until
        #               better segamentation is available for sections that connects to the edge

        #               if limitbysection or sectiononly:
        uselibCV = False
        if uselibCV and (limitbysection or sectiononly):

            #find sections
            count = 0
            maxt1 = bkgrndmean + 2 * bkgrndstddev
            mosaicmax = self.mosaicimage.max()
            stepmaxt = 0.49 * (mosaicmax - maxt1)
            stepscale = 0.8

            axisratiomax = sectionaxisratio * maxsection
            axisratiomin = sectionaxisratio / maxsection
            axisratiolimits = [axisratiomin, axisratiomax]

            while len(sectionarrays) == 0 and maxt1 < mosaicmax:
                count += 1
                regions = None
                minsize1 = onesectionmin
                maxsize1 = multisections
                m = numpy.clip(self.mosaicimage, mint, maxt1)
                regions, image = libCVwrapper.FindRegions(m,
                                                          minsize1,
                                                          maxsize1,
                                                          WoB=False)
                sectionarrays, sectionellipses, sectiondisplaypoints = self.reduceRegions(
                    regions, axisratiolimits, velimit, None)
                minsize1 = stepscale * onesectionmin
                maxt1 += stepmaxt

            self.logger.info('found %i sections after %i iterations' %
                             (len(sectionarrays), count))

        if len(sectiondisplaypoints) == 0:
            if uselibCV and (not limitbysection):
                # rough section by threshold only
                masked_section = numpy.ma.masked_inside(
                    self.mosaicimage, mint, maxt)
                sectionimage = masked_section.mask()
                nlabel = 1
            else:
                # good section as image only - smooth,threshold,size limit etc.
                minsizepixels = onesectionmin * mosaicarea
                maxsizepixels = multisections * mosaicarea
                sectionimage, nsection, sectionellipses = self.regionsByLabel(
                    self.mosaicimage, mint, maxt, minsizepixels, maxsizepixels)
                self.logger.info(
                    'use sectionimage for rastering and found %d good sections'
                    % nsection)
        else:
            sectionimage = polygon.plotPolygons(imshape, sectionarrays)
            nonmissingregion = numpy.where(self.mosaicimage == 0, 0, 1)
            sectionimage = sectionimage * nonmissingregion

        # get section stats
        sectionlabel, nlabels = nd.label(sectionimage)

        # skip everything if no section found
        if nlabels == 0:
            return
        sectionarea = sectionimage.sum()
        sectionmean = nd.mean(self.mosaicimage, labels=sectionlabel)
        #               sectionstddev = nd.standard_deviation(self.mosaicimage,labels=sectionlabel)
        sectionareanum = sectionarea / (self.onesectionarea * mosaicarea)
        sectionareaint = int(round(sectionareanum))

        if abs(sectionareanum - sectionareaint) < modifyarea:
            self.onesectionarea = float(sectionarea) / (sectionareaint *
                                                        mosaicarea)
            areapercenttile = 100 * self.onesectionarea / scale
            self.logger.info('modify per-section area to %f for next round' %
                             areapercenttile)
        t02 = time.time()
        print "----%5.1f----section num %d mean %f" % (
            (t02 - t01), sectionareaint, sectionmean)

        if not (limitbysection or sectiononly):
            sectionimage = None
        else:
            self.regionimage = sectionimage

        if sectiononly:
            regionarrays = sectionarrays
            regionellipses = sectionellipses
            displaypoints = sectiondisplaypoints
        else:

            # find tissue

            if modifyarea > 0.0001:
                nregionmin = max(len(sectionarrays), sectionareaint)
            else:
                nregionmin = max(len(sectionarrays), 1)

            tissuecontrast = (sectionmean - mint) / abs(mint - sectionmean)

            if tissuecontrast > 0:
                black_on_white = True
                white_on_black = False
            else:
                black_on_white = False
                white_on_black = True

            maxt2 = sectionmean + bkgrndstddev * tissuecontrast

            count = 0
            regionarrays = []
            displaypoints = []
            stepscale = 0.2
            while len(
                    regionarrays
            ) < nregionmin and maxt2 * tissuecontrast > sectionmean * tissuecontrast:
                count += 1
                avgt = (mint + maxt2) / 2
                mint2a = avgt - (maxt2 - mint) * tissuecontrast / 2
                maxt2a = avgt + (maxt2 - mint) * tissuecontrast / 2
                m = numpy.clip(self.mosaicimage, mint2a, maxt2a)
                regions, image = libCVwrapper.FindRegions(m,
                                                          minsize,
                                                          maxsize,
                                                          WoB=white_on_black,
                                                          BoW=black_on_white)
                regionarrays, regionellipses, displaypoints = self.reduceRegions(
                    regions, [1.0, self.settings['axis ratio']], velimit,
                    sectionimage)
                minsize = stepscale * minsize
                maxt2 = maxt2 - stepscale * bkgrndstddev * tissuecontrast
                if minsize * mosaicarea < 4:
                    break

            self.logger.info('found %i regions after %i iterations' %
                             (len(regionarrays), count))
            t03 = time.time()
            print "----%5.1f----tissue" % ((t03 - t02), )
            if displaysection:
                displaypoints.extend(sectiondisplaypoints)

        self.regionarrays = regionarrays
        self.regionellipses = regionellipses

        self.setTargets(displaypoints, 'region', block=True)