Esempio n. 1
0
def findBlobs(ccmap,
              thresh,
              maxsize=500,
              minsize=1,
              maxpeaks=1500,
              border=10,
              maxmoment=6.0,
              elim="highest",
              summary=False):
    """
	calls leginon's imagefun.find_blobs
	"""
    totalarea = (ccmap.shape)[0] * (ccmap.shape)[1]
    ccthreshmap = imagefun.threshold(ccmap, thresh)
    percentcov = round(100.0 * float(ccthreshmap.sum()) / float(totalarea), 2)
    #imagefun.find_blobs(image,mask,border,maxblobs,maxblobsize,minblobsize,maxmoment,method)
    if percentcov > 15:
        apDisplay.printWarning("too much coverage in threshold: " +
                               str(percentcov))
        return [], percentcov
    #apImage.arrayToJpeg(ccmap, "dogmap2.jpg")
    #apImage.arrayToJpeg(ccthreshmap, "threshmap2.jpg")
    blobtree = imagefun.find_blobs(ccmap, ccthreshmap, border, maxpeaks * 4,
                                   maxsize, minsize, maxmoment, elim, summary)
    return blobtree, percentcov
Esempio n. 2
0
    def findSquares(self):
        if self.mosaicimagedata is None:
            message = 'You must save the current mosaic image before finding squares on it.'
            self.logger.error(message)
            return
        original_image = self.mosaicimagedata['image']

        message = 'finding squares'
        self.logger.info(message)

        sigma = self.settings['lpf']['sigma']
        kernel = convolver.gaussian_kernel(sigma)
        self.convolver.setKernel(kernel)
        image = self.convolver.convolve(image=original_image)
        self.setImage(image, 'Filtered')

        ## threshold grid bars
        squares_thresh = self.settings['threshold']
        image = imagefun.threshold(image, squares_thresh)
        self.setImage(image, 'Thresholded')

        ## find blobs
        blobs = imagefun.find_blobs(original_image, image,
                                    self.settings['blobs']['border'],
                                    self.settings['blobs']['max'],
                                    self.settings['blobs']['max size'],
                                    self.settings['blobs']['min size'])

        ## use stats to find good ones
        mean_min = self.settings['blobs']['min mean']
        mean_max = self.settings['blobs']['max mean']
        std_min = self.settings['blobs']['min stdev']
        std_max = self.settings['blobs']['max stdev']
        targets = []
        prefs = self.storeSquareFinderPrefs()
        rows, columns = image.shape
        for blob in blobs:
            row = blob.stats['center'][0]
            column = blob.stats['center'][1]
            mean = blob.stats['mean']
            std = blob.stats['stddev']
            stats = leginondata.SquareStatsData(prefs=prefs,
                                                row=row,
                                                column=column,
                                                mean=mean,
                                                stdev=std)
            if (mean_min <= mean <= mean_max) and (std_min <= std <= std_max):
                stats['good'] = True
                ## create a display target
                targets.append((column, row))
            else:
                stats['good'] = False
            self.publish(stats, database=True)

        ## display them
        self.setTargets(targets, 'acquisition')

        message = 'found %s squares' % (len(targets), )
        self.logger.info(message)
Esempio n. 3
0
	def find_edges(self):
		'''
		find edges on the original image
		'''
		if self.__results['original'] is None:
			raise RuntimeError('no original image to find edges on')

		sourceim = self.__results['original']
		filt = self.edges_config['filter']
		sigma = self.edges_config['sigma']
		ab = self.edges_config['abs']
		lpsig = self.edges_config['lpsig']
		edgethresh = self.edges_config['thresh']
		edgesflag = self.edges_config['edges']

		kernel = convolver.gaussian_kernel(lpsig)
		n = len(kernel)
		self.edgefinder.setKernel(kernel)
		smooth = self.edgefinder.convolve(image=sourceim)

		if not edgesflag:
			edges = smooth
		elif filt == 'laplacian3':
			kernel = convolver.laplacian_kernel3
			self.edgefinder.setKernel(kernel)
			edges = self.edgefinder.convolve(image=smooth)
		elif filt == 'laplacian5':
			kernel = convolver.laplacian_kernel5
			self.edgefinder.setKernel(kernel)
			edges = self.edgefinder.convolve(image=smooth)
		elif filt == 'laplacian-gaussian':
			kernel = convolver.laplacian_of_gaussian_kernel(n,sigma)
			self.edgefinder.setKernel(kernel)
			edges = self.edgefinder.convolve(image=smooth)
		elif filt == 'sobel':
			self.edgefinder.setImage(smooth)
			kernel1 = convolver.sobel_row_kernel
			kernel2 = convolver.sobel_col_kernel
			edger = self.edgefinder.convolve(kernel=kernel1)
			edgec = self.edgefinder.convolve(kernel=kernel2)
			edges = numpy.hypot(edger,edgec)
			## zero the image edge effects
			edges[:n] = 0
			edges[:,:n] = 0
			edges[:,-n:] = 0
			edges[-n:] = 0
		else:
			raise RuntimeError('no such filter type: %s' % (filt,))

		if ab and edgesflag:
			edges = numpy.absolute(edges)

		if edgethresh and edgesflag:
			edges = imagefun.threshold(edges, edgethresh)

		self.__update_result('edges', edges)
		if self.save_mrc:
			mrc.write(edges, 'edges.mrc')
        def findSquares(self):
                if self.mosaicimagedata is None:
                        message = 'You must save the current mosaic image before finding squares on it.'
                        self.logger.error(message)
                        return
                original_image = self.mosaicimagedata['image']

                message = 'finding squares'
                self.logger.info(message)

                sigma = self.settings['lpf']['sigma']
                kernel = convolver.gaussian_kernel(sigma)
                self.convolver.setKernel(kernel)
                image = self.convolver.convolve(image=original_image)
                self.setImage(image, 'Filtered')

                ## threshold grid bars
                squares_thresh = self.settings['threshold']
                image = imagefun.threshold(image, squares_thresh)
                self.setImage(image, 'Thresholded')

                ## find blobs
                blobs = imagefun.find_blobs(original_image, image,
                                                                                                                                self.settings['blobs']['border'],
                                                                                                                                self.settings['blobs']['max'],
                                                                                                                                self.settings['blobs']['max size'],
                                                                                                                                self.settings['blobs']['min size'])

                ## use stats to find good ones
                mean_min = self.settings['blobs']['min mean']
                mean_max = self.settings['blobs']['max mean']
                std_min = self.settings['blobs']['min stdev']
                std_max = self.settings['blobs']['max stdev']
                targets = []
                prefs = self.storeSquareFinderPrefs()
                rows, columns = image.shape
                for blob in blobs:
                        row = blob.stats['center'][0]
                        column = blob.stats['center'][1]
                        mean = blob.stats['mean']
                        std = blob.stats['stddev']
                        stats = leginondata.SquareStatsData(prefs=prefs, row=row, column=column, mean=mean, stdev=std)
                        if (mean_min <= mean <= mean_max) and (std_min <= std <= std_max):
                                stats['good'] = True
                                ## create a display target
                                targets.append((column,row))
                        else:
                                stats['good'] = False
                        self.publish(stats, database=True)

                ## display them
                self.setTargets(targets, 'acquisition')

                message = 'found %s squares' % (len(targets),)
                self.logger.info(message)
Esempio n. 5
0
	def threshold_correlation(self, threshold=None):
		'''
		Threshold the correlation image.
		'''
		if self.__results['correlation'] is None:
			raise RuntimeError('need correlation image to threshold')
		self.configure_threshold(threshold)
		cc = self.__results['correlation']
		t = imagefun.threshold(cc, self.threshold)
		self.__update_result('threshold', t)
		if self.save_mrc:
			mrc.write(t, 'threshold.mrc')
	def threshold_correlation(self, threshold=None):
		'''
		Threshold the correlation image.
		'''
		if self.__results['correlation'] is None:
			raise RuntimeError('need correlation image to threshold')
		self.configure_threshold(threshold)
		cc = self.__results['correlation']
		mean = arraystats.mean(cc)
		std = arraystats.std(cc)
		thresh = mean + self.threshold * std
		t = imagefun.threshold(cc, thresh)
		self.__update_result('threshold', t)
		if self.save_mrc:
			mrc.write(t, 'threshold.mrc')
def findBlobs(ccmap, thresh, maxsize=500, minsize=1, maxpeaks=1500, border=10, 
	  maxmoment=6.0, elim= "highest", summary=False):
	"""
	calls leginon's imagefun.find_blobs
	"""
	totalarea = (ccmap.shape)[0]*(ccmap.shape)[1]
	ccthreshmap = imagefun.threshold(ccmap, thresh)
	percentcov  =  round(100.0*float(ccthreshmap.sum())/float(totalarea),2)
	#imagefun.find_blobs(image,mask,border,maxblobs,maxblobsize,minblobsize,maxmoment,method)
	if percentcov > 15:
		apDisplay.printWarning("too much coverage in threshold: "+str(percentcov))
		return [],percentcov
	#apImage.arrayToJpeg(ccmap, "dogmap2.jpg")
	#apImage.arrayToJpeg(ccthreshmap, "threshmap2.jpg")
	blobtree = imagefun.find_blobs(ccmap, ccthreshmap, border, maxpeaks*4,
	  maxsize, minsize, maxmoment, elim, summary)
	return blobtree, percentcov
def fitFirstCTFNode(pow, rpixelsize, defocus, ht):
	filter = ndimage.gaussian_filter(pow,3)
	grad = ndimage.gaussian_gradient_magnitude(filter,3)
	thr = imagefun.threshold(grad,grad.mean()+3*grad.std())
	if defocus:
		z = abs(defocus)
		s = calculateFirstNode(ht,z)
		dmean = max(0.8*s/rpixelsize, 30)
	else:
		shape = pow.shape
		r = 20
		center = ( shape[0] / 2, shape[1] / 2 ) 
		grad[center[0]-r: center[0]+r, center[1]-r: center[1]+r] = 0
		peak = ndimage.maximum_position(grad)
		dmean = math.hypot(peak[0] - center[0], peak[1] - center[1])
	drange = max(dmean / 4, 10)
	eparams = find_ast_ellipse(grad,thr,dmean,drange)
	if eparams:
		z0, zast, ast_ratio, alpha = getAstigmaticDefocii(eparams,rpixelsize, ht)
		return z0,zast,ast_ratio, alpha, eparams
Esempio n. 9
0
def fitFirstCTFNode(pow, rpixelsize, defocus, ht):
    filter = ndimage.gaussian_filter(pow, 3)
    grad = ndimage.gaussian_gradient_magnitude(filter, 3)
    thr = imagefun.threshold(grad, grad.mean() + 3 * grad.std())
    if defocus:
        z = abs(defocus)
        s = calculateFirstNode(ht, z)
        dmean = max(0.8 * s / rpixelsize, 30)
    else:
        shape = pow.shape
        r = 20
        center = (shape[0] / 2, shape[1] / 2)
        grad[center[0] - r:center[0] + r, center[1] - r:center[1] + r] = 0
        peak = ndimage.maximum_position(grad)
        dmean = math.hypot(peak[0] - center[0], peak[1] - center[1])
    drange = max(dmean / 4, 10)
    eparams = find_ast_ellipse(grad, thr, dmean, drange)
    if eparams:
        z0, zast, ast_ratio, alpha = getAstigmaticDefocii(
            eparams, rpixelsize, ht)
        return z0, zast, ast_ratio, alpha, eparams
Esempio n. 10
0
	def findEdges(self, image):
		gk = gaussian(image.shape, 1.2)
		srk = sobel_row(image.shape)
		sck = sobel_col(image.shape)

		imfft = ffteng.transform(image)
		gkfft = ffteng.transform(gk)
		srkfft = ffteng.transform(srk)
		sckfft = ffteng.transform(sck)

		smooth = Numeric.multiply(imfft, gkfft)

		refft = Numeric.multiply(smooth, srkfft)
		cefft = Numeric.multiply(smooth, sckfft)

		re = ffteng.itransform(refft)
		ce = ffteng.itransform(cefft)

		edges = Numeric.hypot(re,ce)

		## convolution leaves invalid borders
		# copy rows
		print 'clean up'
		edges[0] = edges[1]
		edges[-1] = edges[-2]
		# copy cols
		edges[:,0] = edges[:,1]
		edges[:,-1] = edges[:,-2]

		# threshold
		print 'threshold'
		edges = imagefun.zscore(edges)
		print 'clip'
		# works for everything except test_square7
		#edges = Numeric.clip(edges, -0.5, 1.0)
		edges = imagefun.threshold(edges, 0.8)

		print 'done'
		return edges
        def findEdges(self, image):
                gk = gaussian(image.shape, 1.2)
                srk = sobel_row(image.shape)
                sck = sobel_col(image.shape)

                imfft = ffteng.transform(image)
                gkfft = ffteng.transform(gk)
                srkfft = ffteng.transform(srk)
                sckfft = ffteng.transform(sck)

                smooth = Numeric.multiply(imfft, gkfft)

                refft = Numeric.multiply(smooth, srkfft)
                cefft = Numeric.multiply(smooth, sckfft)

                re = ffteng.itransform(refft)
                ce = ffteng.itransform(cefft)

                edges = Numeric.hypot(re,ce)

                ## convolution leaves invalid borders
                # copy rows
                print 'clean up'
                edges[0] = edges[1]
                edges[-1] = edges[-2]
                # copy cols
                edges[:,0] = edges[:,1]
                edges[:,-1] = edges[:,-2]

                # threshold
                print 'threshold'
                edges = imagefun.zscore(edges)
                print 'clip'
                # works for everything except test_square7
                #edges = Numeric.clip(edges, -0.5, 1.0)
                edges = imagefun.threshold(edges, 0.8)

                print 'done'
                return edges
Esempio n. 12
0
	def find_edges(self):
		'''
		find edges on the original image
		'''
		if self.__results['original'] is None:
			raise RuntimeError('no original image to find edges on')

		sourceim = self.__results['original']
		sigma = self.edges_config['lpsig']
		edgethresh = self.edges_config['thresh']

		smooth = scipy.ndimage.gaussian_filter(sourceim, sigma)
		mrc.write(smooth, 'smooth.mrc')

		edges = scipy.ndimage.generic_gradient_magnitude(smooth, derivative=scipy.ndimage.sobel)

		if edgethresh:
			edges = imagefun.threshold(edges, edgethresh)

		self.__update_result('edges', edges)
		if self.save_mrc:
			mrc.write(edges, 'edges.mrc')
	def find_edges(self):
		'''
		find edges on the original image
		'''
		if self.__results['original'] is None:
			raise RuntimeError('no original image to find edges on')

		sourceim = self.__results['original']
		sigma = self.edges_config['lpsig']
		edgethresh = self.edges_config['thresh']

		smooth = scipy.ndimage.gaussian_filter(sourceim, sigma)
		if self.save_mrc:
			mrc.write(smooth, 'smooth.mrc')

		edges = scipy.ndimage.generic_gradient_magnitude(smooth, derivative=scipy.ndimage.sobel)

		if edgethresh:
			edges = imagefun.threshold(edges, edgethresh)

		self.__update_result('edges', edges)
		if self.save_mrc:
			mrc.write(edges, 'edges.mrc')
def find_ast_ellipse(grad,thr,dmean,drange):
        mrc.write(grad,'grad.mrc')
        mrc.write(thr,'thr.mrc')
        maxsize=4*(drange)*(drange)
        blobs = imagefun.find_blobs(grad,thr,maxblobsize=maxsize,minblobsize=0)
        points = []
        goods = []
        # find isolated blobs in the range
        for blob in blobs:
                if blob.stats['size']==0:
                        points.append(blob.stats['center'])
                else:
                        points.append(blob.stats['maximum_position'])
        shape = grad.shape
        center = map((lambda x: x / 2), shape)
        for point in points:
                d = math.hypot(point[0]-center[0],point[1]-center[1])
                if d > dmean-drange and d < dmean+drange:
                        goods.append(point)
        # divide the continuous blob into wedges and find centers of each
        offsets = []
        angles = []
        division = 32
        for i in range(0,division):
                angles.append(i * math.pi / division)
        while angles:
                angle = angles.pop()
                extra = 0
                blobs = []
                while len(blobs)==0 and extra < dmean:
                        # move out until a blob is found
                        offset = ((dmean+extra)*math.cos(angle)-(drange+extra)+center[0],(dmean+extra)*math.sin(angle)-(drange+extra)+center[1])
                        dim = (drange+extra,drange+extra)
                        gsample = grad[offset[0]:offset[0]+2*dim[0], offset[1]:offset[1]+2*dim[1]]
                        sample = imagefun.threshold(gsample,grad.mean()+3*grad.std())
                        # pad the edge to 0 so that blobs including the edge can be found
                        sample[0:1,:]=0
                        sample[-1:,:]=0
                        sample[:,0:1]=0
                        sample[:,-1:]=0
                        #mrc.write(sample,os.path.join('sample%d.mrc'%(division-len(angles))))
                        maxblobsize = dim[0]*dim[1]
                        blobs = imagefun.find_blobs(gsample,sample,maxblobsize=maxsize,border=5+extra)
                        distances = []
                        gooddistances = []
                        for blob in blobs:
                                position = blob.stats['maximum_position']
                                newposition = (position[0]+offset[0],position[1]+offset[1])
                                d = math.hypot(newposition[0]-center[0],newposition[1]-center[1])
                                distances.append(d)
                                if d > dmean-drange:
                                        gooddistances.append(d)
                        if len(gooddistances) > 0:
                                for i,blob in enumerate(blobs):
                                        position = blob.stats['maximum_position']
                                        newposition = (position[0]+offset[0],position[1]+offset[1])
                                        if distances[i] == min(gooddistances):
                                                #print division - len(angles),distances[i],position
                                                symposition = (center[0]*2-newposition[0],center[1]*2-newposition[1])
                                                goods.append(newposition)
                                                goods.append(symposition)
                                                break
                        extra += drange / 2
        if len(goods) > 6:
                eparams =  ellipse.solveEllipseB2AC(goods)
                return eparams
        else:
                return None
Esempio n. 15
0
def findPeaksInMapPlus(ccmaxmap, file, num, params, template, tmplmask,
                       anglemap):
    threshold = float(params["thresh"])
    bin = int(params["bin"])
    diam = float(params["diam"])
    apix = float(params["apix"])
    olapmult = float(params["overlapmult"])
    maxpeaks = int(params["maxpeaks"])
    pixrad = diam / apix / 2.0 / float(bin)
    #MAXBLOBSIZE ==> 2x AREA OF PARTICLE
    maxblobsize = int(round(math.pi *
                            (apix * diam / float(bin))**2 / 2.0, 0)) + 1
    totalarea = (ccmaxmap.shape)[0]**2

    print " ... threshold", threshold

    outfile = "pikfiles/" + file + "." + str(num) + ".pik"
    if (os.path.exists(outfile)):
        os.remove(outfile)
        print " ... removed existing file:", outfile

    for i in range(5):
        thresh = threshold + float(i - 2) * 0.05
        ccthreshmap = imagefun.threshold(ccmaxmap, thresh)
        percentcover = round(
            100.0 * float(ccthreshmap.sum()) / float(totalarea), 3)
        blobs = imagefun.find_blobs(ccmaxmap, ccthreshmap, 6, maxpeaks * 4,
                                    maxblobsize, 2, 5, "highest")
        tstr = "%.2f" % thresh
        lbstr = "%4d" % len(blobs)
        pcstr = "%.2f" % percentcover
        if (thresh == threshold):
            print " ... *** selected threshold: "+tstr+" gives "+lbstr+" peaks ("+\
                    pcstr+"% coverage ) ***"
        else:
            print " ...      varying threshold: "+tstr+" gives "+lbstr+" peaks ("+\
                    pcstr+"% coverage )"

    ccthreshmap = imagefun.threshold(ccmaxmap, threshold)
    percentcover = round(100.0 * float(ccthreshmap.sum()) / float(totalarea),
                         2)

    #numeric_to_jpg(ccthreshmap,"ccthreshmap.jpg")
    blobs = imagefun.find_blobs(ccmaxmap, ccthreshmap, 6, maxpeaks * 4,
                                maxblobsize, 2, 5, "highest")
    if (len(blobs) > maxpeaks):
        print " !!! more than maxpeaks (" + str(
            maxpeaks) + ") peaks, selecting only top peaks"
        blobs.sort(blob_compare)
        blobs = blobs[0:maxpeaks]

    del ccthreshmap

    #find_blobs(image,mask,border,maxblobs,maxblobsize,minblobsize)
    print "Template "+str(num)+": Found",len(blobs),"peaks ("+\
            str(percentcover)+"% coverage)"
    if (percentcover > 10):
        print " !!! WARNING: thresholding covers more than 10% of image"

    cutoff = olapmult * pixrad  #1.5x particle radius in pixels
    removeOverlappingBlobs(blobs, cutoff)

    blobs.sort(blob_compare)

    #blobs = calc_corrcoeffs(blobs,file,bin,template,tmplmask,anglemap)
    blobs = fake_corrcoeffs(blobs, file, bin, template, tmplmask, anglemap)

    #WRITE PIK FILE
    f = open(outfile, 'w')
    f.write(
        "#filename x y mean stdev corr_coeff peak_size templ_num angle moment\n"
    )
    for blob in blobs:
        row = blob.stats['center'][0]
        col = blob.stats['center'][1]
        mean = blob.stats['mean']
        std = blob.stats['stddev']
        rho = blob.stats['corrcoeff']
        mom = blob.stats['moment']
        size = blob.stats['n']
        mean_str = "%.4f" % mean
        std_str = "%.4f" % std
        rho_str = "%.4f" % rho
        mom_str = "%.4f" % mom

        #filename x y mean stdev corr_coeff peak_size templ_num angle moment
        out = file+".mrc "+str(int(col)*bin)+" "+str(int(row)*bin)+ \
                " "+mean_str+" "+std_str+" "+rho_str+" "+str(int(size))+ \
                " "+str(num)+" 0 "+mom_str
        f.write(str(out) + "\n")
    f.close()

    drawBlobs(ccmaxmap, blobs, file, num, bin, pixrad)

    return blobs
def find_ast_ellipse(grad,thr,dmean,drange):
	mrc.write(grad,'grad.mrc')
	mrc.write(thr,'thr.mrc')
	maxsize=4*(drange)*(drange)
	blobs = imagefun.find_blobs(grad,thr,maxblobsize=maxsize,minblobsize=0)
	points = []
	goods = []
	# find isolated blobs in the range
	for blob in blobs:
		if blob.stats['size']==0:
			points.append(blob.stats['center'])
		else:
			points.append(blob.stats['maximum_position'])
	shape = grad.shape
	center = map((lambda x: x / 2), shape)
	for point in points:
		d = math.hypot(point[0]-center[0],point[1]-center[1])
		if d > dmean-drange and d < dmean+drange:
			goods.append(point)
	# divide the continuous blob into wedges and find centers of each
	offsets = []
	angles = []
	division = 32
	for i in range(0,division):
		angles.append(i * math.pi / division)
	while angles:
		angle = angles.pop()
		extra = 0
		blobs = []
		while len(blobs)==0 and extra < dmean:
			# move out until a blob is found
			offset = ((dmean+extra)*math.cos(angle)-(drange+extra)+center[0],(dmean+extra)*math.sin(angle)-(drange+extra)+center[1])
			dim = (drange+extra,drange+extra)
			gsample = grad[offset[0]:offset[0]+2*dim[0], offset[1]:offset[1]+2*dim[1]]
			sample = imagefun.threshold(gsample,grad.mean()+3*grad.std())
			# pad the edge to 0 so that blobs including the edge can be found
			sample[0:1,:]=0
			sample[-1:,:]=0
			sample[:,0:1]=0
			sample[:,-1:]=0
			#mrc.write(sample,os.path.join('sample%d.mrc'%(division-len(angles))))
			maxblobsize = dim[0]*dim[1]
			blobs = imagefun.find_blobs(gsample,sample,maxblobsize=maxsize,border=5+extra)
			distances = []
			gooddistances = []
			for blob in blobs:
				position = blob.stats['maximum_position']
				newposition = (position[0]+offset[0],position[1]+offset[1])
				d = math.hypot(newposition[0]-center[0],newposition[1]-center[1])
				distances.append(d)
				if d > dmean-drange:
					gooddistances.append(d)
			if len(gooddistances) > 0:
				for i,blob in enumerate(blobs):
					position = blob.stats['maximum_position']
					newposition = (position[0]+offset[0],position[1]+offset[1])
					if distances[i] == min(gooddistances):
						#print division - len(angles),distances[i],position
						symposition = (center[0]*2-newposition[0],center[1]*2-newposition[1])
						goods.append(newposition)
						goods.append(symposition)
						break
			extra += drange / 2
	if len(goods) > 6:
		eparams =  ellipse.solveEllipseB2AC(goods)
		return eparams
	else:
		return None
def findPeaksInMapPlus(ccmaxmap,file,num,params,template,tmplmask,anglemap):
	threshold =   float(params["thresh"])
	bin =         int(params["bin"])
	diam =        float(params["diam"])
	apix =        float(params["apix"])
	olapmult =    float(params["overlapmult"])
	maxpeaks =    int(params["maxpeaks"])
	pixrad =      diam/apix/2.0/float(bin)
	#MAXBLOBSIZE ==> 2x AREA OF PARTICLE
	maxblobsize = int(round(math.pi*(apix*diam/float(bin))**2/2.0,0))+1
	totalarea =   (ccmaxmap.shape)[0]**2

	print " ... threshold",threshold

	outfile="pikfiles/"+file+"."+str(num)+".pik"
	if (os.path.exists(outfile)):
		os.remove(outfile)
		print " ... removed existing file:",outfile

	for i in range(5):
		thresh      = threshold + float(i-2)*0.05
		ccthreshmap = imagefun.threshold(ccmaxmap,thresh)
		percentcover =  round(100.0*float(ccthreshmap.sum())/float(totalarea),3)
		blobs       = imagefun.find_blobs(ccmaxmap,ccthreshmap,6,maxpeaks*4,maxblobsize,2,5,"highest")
		tstr  = "%.2f" % thresh
		lbstr = "%4d" % len(blobs)
		pcstr = "%.2f" % percentcover
		if(thresh == threshold):
			print " ... *** selected threshold: "+tstr+" gives "+lbstr+" peaks ("+\
				pcstr+"% coverage ) ***"
		else:
			print " ...      varying threshold: "+tstr+" gives "+lbstr+" peaks ("+\
				pcstr+"% coverage )"

	ccthreshmap = imagefun.threshold(ccmaxmap,threshold)
	percentcover =  round(100.0*float(ccthreshmap.sum())/float(totalarea),2)

	#numeric_to_jpg(ccthreshmap,"ccthreshmap.jpg")
	blobs = imagefun.find_blobs(ccmaxmap, ccthreshmap, 6, maxpeaks*4, maxblobsize, 2,5,"highest")
	if(len(blobs) > maxpeaks):
		print " !!! more than maxpeaks ("+str(maxpeaks)+") peaks, selecting only top peaks"
		blobs.sort(blob_compare)
		blobs = blobs[0:maxpeaks]

	del ccthreshmap

	#find_blobs(image,mask,border,maxblobs,maxblobsize,minblobsize)
	print "Template "+str(num)+": Found",len(blobs),"peaks ("+\
		str(percentcover)+"% coverage)"
	if(percentcover > 10):
		print " !!! WARNING: thresholding covers more than 10% of image"

	cutoff = olapmult*pixrad	#1.5x particle radius in pixels
	removeOverlappingBlobs(blobs,cutoff)

	blobs.sort(blob_compare)

	#blobs = calc_corrcoeffs(blobs,file,bin,template,tmplmask,anglemap)
	blobs = fake_corrcoeffs(blobs,file,bin,template,tmplmask,anglemap)

	#WRITE PIK FILE
	f=open(outfile, 'w')
	f.write("#filename x y mean stdev corr_coeff peak_size templ_num angle moment\n")
	for blob in blobs:
		row = blob.stats['center'][0]
		col = blob.stats['center'][1]
		mean = blob.stats['mean']
		std = blob.stats['stddev']
		rho = blob.stats['corrcoeff']
		mom = blob.stats['moment']
		size = blob.stats['n']
		mean_str = "%.4f" % mean
		std_str = "%.4f" % std
		rho_str = "%.4f" % rho
		mom_str = "%.4f" % mom

		#filename x y mean stdev corr_coeff peak_size templ_num angle moment
		out = file+".mrc "+str(int(col)*bin)+" "+str(int(row)*bin)+ \
			" "+mean_str+" "+std_str+" "+rho_str+" "+str(int(size))+ \
			" "+str(num)+" 0 "+mom_str
		f.write(str(out)+"\n")
	f.close()

	drawBlobs(ccmaxmap,blobs,file,num,bin,pixrad)

	return blobs
 def _process(self, input):
         min = arraystats.min(input.image)
         max = arraystats.max(input.image)
         cutoff = (max - min) / self.cutoff.get()
         return self.outputclass(input.image,
                                                                                                         imagefun.threshold(input.image, cutoff))
Esempio n. 19
0
 def _process(self, input):
     min = arraystats.min(input.image)
     max = arraystats.max(input.image)
     cutoff = (max - min) / self.cutoff.get()
     return self.outputclass(input.image,
                             imagefun.threshold(input.image, cutoff))