def _process(self, input): border = self.border.get() maxblobs = self.maxblobs.get() minblobsize = self.minblobsize.get() maxblobsize = self.maxblobsize.get() scale = self.scale.getSelectedValue() threshold = self.threshold.get() thresholdpoint = self.thresholdpoint.get() if scale is None: scale = 1 else: scale = int(scale.split('/')[-1]) try: blobs = imagefun.find_blobs(input.image[::scale, ::scale], input.mask[::scale, ::scale], border/scale, maxblobs, maxblobsize/scale, minblobsize/scale) except ValueError: blobs = [] thresholdedblobs = [] for blob in blobs: blobvalues = list(blob.value_list) blobvalues.sort() thresholdvalue = blobvalues[int(len(blobvalues) * thresholdpoint)] if thresholdvalue < threshold: thresholdedblobs.append(blob) blobs = thresholdedblobs targets = map(lambda b: (scale*b.stats['center'][1], scale*b.stats['center'][0]), blobs) return self.outputclass(input.image, targets)
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 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)
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)
def find_blobs(self): ''' find blobs on a thresholded image ''' if None in (self.__results['threshold'],self.__results['correlation']): raise RuntimeError('need correlation image and threshold image to find blobs') im = self.__results['correlation'] mask = self.__results['threshold'] border = self.blobs_config['border'] maxsize = self.blobs_config['maxblobsize'] maxblobs = self.blobs_config['maxblobs'] blobs = imagefun.find_blobs(im, mask, border, maxblobs, maxsize) self.__update_result('blobs', blobs)
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 find_blobs(self, picks=None): ''' find blobs on a thresholded image ''' if picks is None: if self.__results['threshold'] is None or self.__results['correlation'] is None: raise RuntimeError('need correlation image and threshold image to find blobs') im = self.__results['correlation'] mask = self.__results['threshold'] border = self.blobs_config['border'] maxsize = self.blobs_config['maxblobsize'] minsize = self.blobs_config['minblobsize'] maxblobs = self.blobs_config['maxblobs'] blobs = imagefun.find_blobs(im, mask, border, maxblobs, maxsize, minsize) else: picks = self.swapxy(picks) blobs = self.points_to_blobs(picks) self.__update_result('blobs', blobs)
def _process(self, input): border = self.border.get() maxblobs = self.maxblobs.get() minblobsize = self.minblobsize.get() maxblobsize = self.maxblobsize.get() scale = self.scale.getSelectedValue() threshold = self.threshold.get() thresholdpoint = self.thresholdpoint.get() if scale is None: scale = 1 else: scale = int(scale.split('/')[-1]) try: blobs = imagefun.find_blobs(input.image[::scale, ::scale], input.mask[::scale, ::scale], border / scale, maxblobs, maxblobsize / scale, minblobsize / scale) except ValueError: blobs = [] thresholdedblobs = [] for blob in blobs: blobvalues = list(blob.value_list) blobvalues.sort() thresholdvalue = blobvalues[int(len(blobvalues) * thresholdpoint)] if thresholdvalue < threshold: thresholdedblobs.append(blob) blobs = thresholdedblobs targets = map( lambda b: (scale * b.stats['center'][1], scale * b.stats['center'][0]), blobs) return self.outputclass(input.image, targets)
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
image = mrc.read('hftest.mrc') t = timer.Timer() #edgeimage = gradient(image) edgeimage = edges(image) t.reset() houghcircleimage = houghCircle(edgeimage, 300, [28,28]) houghcircleimage = numpy.clip(houghcircleimage, 100, 30000) houghcircleimage = houghcircleimage - 100 t.reset() mask = houghcircleimage #numpy.ones(houghcircleimage.shape) blobs = imagefun.find_blobs(houghcircleimage, mask, maxblobsize=256) blobimage = numpy.zeros(houghcircleimage.shape) for blob in blobs: if blob.stats['n'] > 16: i, j = blob.stats['center'] i, j = int(round(i)), int(round(j)) blobimage[i, j] = 100 #blob.stats['n'] blobimage[i-1:i+2, j-1:j+2] = blobimage[i-1:i+2, j-1:j+2] + 100 # houghlineimage = houghLine(houghcircleimage, 101)[:,:,0] houghlineimage = houghLine(blobimage, 1)[:,:,0] tolerance = 5 angle = 90 for theta in range(houghlineimage.shape[1]/2): sum = 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