Changeset 3815


Ignore:
Timestamp:
Feb 11, 2019 11:26:52 AM (4 years ago)
Author:
toby
Message:

Add recalibrate & more image load/set routines

Location:
trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIfiles.py

    r3814 r3815  
    743743        File.write(key+':'+str(data[key])+'\n')
    744744    File.close()
    745    
     745
     746def RereadImageData(ImageReaderlist,imagefile,ImageTag=None,FormatName=''):
     747    '''Read a single image with an image importer. This is called to
     748    reread an image after it has already been imported, so it is not
     749    necessary to reload metadata.
     750
     751    Based on :func:`GetImageData.GetImageData` which this can replace
     752    where imageOnly=True
     753
     754    :param list ImageReaderlist: list of Reader objects for images
     755    :param str imagefile: name of image file
     756    :param int/str ImageTag: specifies a particular image to be read from a file.
     757      First image is read if None (default).
     758    :param str formatName: the image reader formatName
     759
     760    :returns: an image as a numpy array
     761    '''
     762    # determine which formats are compatible with this file
     763    primaryReaders = []
     764    secondaryReaders = []
     765    for rd in ImageReaderlist:
     766        flag = rd.ExtensionValidator(imagefile)
     767        if flag is None:
     768            secondaryReaders.append(rd)
     769        elif flag:
     770            if not FormatName:
     771                primaryReaders.append(rd)
     772            elif FormatName == rd.formatName:
     773                primaryReaders.append(rd)
     774    if len(secondaryReaders) + len(primaryReaders) == 0:
     775        print('Error: No matching format for file '+imagefile)
     776        raise Exception('No image read')
     777    errorReport = ''
     778    if not imagefile:
     779        return
     780    for rd in primaryReaders+secondaryReaders:
     781        rd.ReInitialize() # purge anything from a previous read
     782        rd.errors = "" # clear out any old errors
     783        if not rd.ContentsValidator(imagefile): # rejected on cursory check
     784            errorReport += "\n  "+rd.formatName + ' validator error'
     785            if rd.errors:
     786                errorReport += ': '+rd.errors
     787                continue
     788        flag = rd.Reader(imagefile,None,blocknum=ImageTag)
     789        if flag: # this read succeeded
     790            if rd.Image is None:
     791                raise Exception('No image read. Strange!')
     792            if GSASIIpath.GetConfigValue('Transpose'):
     793                print ('Transposing Image!')
     794                rd.Image = rd.Image.T
     795            #rd.readfilename = imagefile
     796            return rd.Image
     797    else:
     798        print('Error reading file '+imagefile)
     799        print('Error messages(s)\n'+errorReport)
     800        raise Exception('No image read')
     801
     802def readMasks(filename,masks,ignoreThreshold):
     803    '''Read a GSAS-II masks file'''
     804    File = open(filename,'r')
     805    save = {}
     806    oldThreshold = masks['Thresholds'][0]
     807    S = File.readline()
     808    while S:
     809        if S[0] == '#':
     810            S = File.readline()
     811            continue
     812        [key,val] = S.strip().split(':',1)
     813        if key in ['Points','Rings','Arcs','Polygons','Frames','Thresholds']:
     814            if ignoreThreshold and key == 'Thresholds':
     815                S = File.readline()
     816                continue
     817            save[key] = eval(val)
     818            if key == 'Thresholds':
     819                save[key][0] = oldThreshold
     820                save[key][1][1] = min(oldThreshold[1],save[key][1][1])
     821        S = File.readline()
     822    File.close()
     823    masks.update(save)
     824    # CleanupMasks
     825    for key in ['Points','Rings','Arcs','Polygons']:
     826        masks[key] = masks.get(key,[])
     827        masks[key] = [i for i in masks[key] if len(i)]
  • trunk/GSASIIimage.py

    r3655 r3815  
    540540    return tam.T
    541541   
    542 def ImageRecalibrate(G2frame,data,masks):
     542def ImageRecalibrate(G2frame,ImageZ,data,masks):
    543543    '''Called to repeat the calibration on an image, usually called after
    544544    calibration is done initially to improve the fit.
     545
     546    :param G2frame: The top-level GSAS-II frame or None, to skip plotting
     547    :param np.Array ImageZ: the image to calibrate
     548    :param dict data: the Controls dict for the image
     549    :param dict masks: a dict with masks
     550    :returns: a list containing vals,varyList,sigList,parmDict
    545551    '''
    546552    import ImageCalibrants as calFile
     
    580586    wave = data['wavelength']
    581587    frame = masks['Frames']
    582     tam = ma.make_mask_none(G2frame.ImageZ.shape)
     588    tam = ma.make_mask_none(ImageZ.shape)
    583589    if frame:
    584590        tam = ma.mask_or(tam,MakeFrameMask(data,frame))
     
    591597            break
    592598        ellipse = GetEllipse(dsp,data)
    593         Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,ma.array(G2frame.ImageZ,mask=tam))[0]
     599        Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,ma.array(ImageZ,mask=tam))[0]
    594600        if Ring:
    595601            if iH >= skip:
     
    621627        data['ellipses'].append(copy.deepcopy(ellipse+('b',)))   
    622628    print ('calibration time = %.3f'%(time.time()-time0))
    623     G2plt.PlotImage(G2frame,newImage=True)       
     629    if G2frame:
     630        G2plt.PlotImage(G2frame,newImage=True)       
    624631    return [vals,varyList,sigList,parmDict]
    625632           
  • trunk/GSASIIimgGUI.py

    r3814 r3815  
    192192               
    193193    def OnRecalibrate(event):
    194         G2img.ImageRecalibrate(G2frame,data,masks)
     194        G2img.ImageRecalibrate(G2frame,G2frame.ImageZ,data,masks)
    195195        wx.CallLater(100,UpdateImageControls,G2frame,data,masks)
    196196       
     
    217217                    Mid = G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Masks')
    218218                    Masks = G2frame.GPXtree.GetItemPyData(Mid)
    219                     vals,varyList,sigList,parmDict = G2img.ImageRecalibrate(G2frame,Data,Masks)
     219                    vals,varyList,sigList,parmDict = G2img.ImageRecalibrate(
     220                        G2frame,G2frame.ImageZ,Data,Masks)
    220221                    sigList = list(sigList)
    221222                    if 'dist' not in varyList:
     
    14361437            if dlg.ShowModal() == wx.ID_OK:
    14371438                filename = dlg.GetPath()
    1438                 File = open(filename,'r')
    1439                 save = {}
    1440                 oldThreshold = data['Thresholds'][0]
    1441                 S = File.readline()
    1442                 while S:
    1443                     if S[0] == '#':
    1444                         S = File.readline()
    1445                         continue
    1446                     [key,val] = S.strip().split(':',1)
    1447                     if key in ['Points','Rings','Arcs','Polygons','Frames','Thresholds']:
    1448                         if ignoreThreshold and key == 'Thresholds':
    1449                             S = File.readline()
    1450                             continue
    1451                         save[key] = eval(val)
    1452                         if key == 'Thresholds':
    1453                             save[key][0] = oldThreshold
    1454                             save[key][1][1] = min(oldThreshold[1],save[key][1][1])
    1455                     S = File.readline()
    1456                 File.close()
    1457                 data.update(save)
    1458                 CleanupMasks(data)
     1439                G2fil.readMasks(filename,data,ignoreThreshold)
    14591440                wx.CallAfter(UpdateMasks,G2frame,data)
    14601441                G2plt.PlotExposedImage(G2frame,event=event)               
  • trunk/GSASIIscriptable.py

    r3814 r3815  
    576576import GSASIIElem as G2elem
    577577import GSASIIfiles as G2fil
     578import GSASIIimage as G2img
    578579
    579580# Delay imports to not slow down small scripts that don't need them
     
    584585
    585586def LoadG2fil():
    586     """Delay importing this module, it is slow"""
     587    """Setup GSAS-II importers. Delay importing this module, it is slow"""
    587588    if len(Readers['Pwdr']) > 0: return
    588589    # initialize imports
     
    11601161            into[:] = from_
    11611162
     1163def GetCorrImage(ImageReaderlist,proj,imageRef):
     1164    '''Gets image & applies dark, background & flat background corrections.
     1165    based on :func:`GSASIIimgGUI.GetImageZ`
     1166
     1167    :param list ImageReaderlist: list of Reader objects for images
     1168    :param object ImageReaderlist: list of Reader objects for images
     1169    :param imageRef: A reference to the desired image. Either the Image
     1170      tree name (str), the image's index (int) or
     1171      a image object (:class:`G2Image`)
     1172
     1173    :return: array sumImg: corrected image for background/dark/flat back
     1174    '''
     1175    ImgObj = proj.image(imageRef)
     1176    Controls = ImgObj.data['Image Controls']
     1177    formatName = Controls.get('formatName','')
     1178    imagefile = ImgObj.data['data'][1]
     1179    ImageTag = None # fix this for multiimage files
     1180    sumImg = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
     1181    if sumImg is None:
     1182        return []
     1183    darkImg = False
     1184    if 'dark image' in Controls:
     1185        darkImg,darkScale = Controls['dark image']
     1186        if darkImg:
     1187            dImgObj = proj.image(darkImg)
     1188            formatName = dImgObj.data['Image Controls'].get('formatName','')
     1189            imagefile = dImgObj.data['data'][1]
     1190            ImageTag = None # fix this for multiimage files
     1191            darkImg = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
     1192            if darkImg is None:
     1193                raise Exception('Error reading dark image {}'.format(imagefile))
     1194            sumImg += np.array(darkImage*darkScale,dtype='int32')
     1195    if 'background image' in Controls:
     1196        backImg,backScale = Controls['background image']           
     1197        if backImg:     #ignores any transmission effect in the background image
     1198            bImgObj = proj.image(backImg)
     1199            formatName = bImgObj.data['Image Controls'].get('formatName','')
     1200            imagefile = bImgObj.data['data'][1]
     1201            ImageTag = None # fix this for multiimage files
     1202            backImg = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
     1203            if backImage is None:
     1204                raise Exception('Error reading background image {}'.format(imagefile))
     1205            if darkImg:
     1206                backImage += np.array(darkImage*darkScale/backScale,dtype='int32')
     1207            else:
     1208                sumImg += np.array(backImage*backScale,dtype='int32')
     1209    if 'Gain map' in Controls:
     1210        gainMap = Controls['Gain map']
     1211        if gainMap:
     1212            gImgObj = proj.image(gainMap)
     1213            formatName = gImgObj.data['Image Controls'].get('formatName','')
     1214            imagefile = gImgObj.data['data'][1]
     1215            ImageTag = None # fix this for multiimage files
     1216            GMimage = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
     1217            if GMimage is None:
     1218                raise Exception('Error reading Gain map image {}'.format(imagefile))
     1219            sumImg = sumImg*GMimage/1000
     1220    sumImg -= int(Controls.get('Flat Bkg',0))
     1221    Imax = np.max(sumImg)
     1222    Controls['range'] = [(0,Imax),[0,Imax]]
     1223    return np.asarray(sumImg,dtype='int32')
    11621224
    11631225class G2ObjectWrapper(object):
     
    31233185                     'DetDepthRef', 'showLines'],
    31243186        'str': ['SampleShape', 'binType', 'formatName', 'color',
    3125                     'type', 'calibrant'],
     3187                    'type', ],
    31263188        'list': ['GonioAngles', 'IOtth', 'LRazimuth', 'Oblique', 'PolaVal',
    31273189                   'SampleAbs', 'center', 'ellipses', 'linescan',
    31283190                    'pixelSize', 'range', 'ring', 'rings', 'size', ],
    31293191        'dict': ['varylist'],
    3130 #        'image': ['background image', 'dark image', 'Gain map'],
    31313192        }
    31323193    '''Defines the items known to exist in the Image Controls tree section
    31333194    and their data types.
    31343195    '''
     3196    # special handling: 'background image', 'dark image', 'Gain map',
     3197    #   'calibrant'
    31353198
    31363199    def __init__(self, data, name, proj):
     
    32063269        return matchList
    32073270
     3271    def setCalibrant(self,calib):
     3272        '''Set a calibrant for the current image
     3273
     3274        :param str calib: specifies a calibrant name which must be one of
     3275          the entries in file ImageCalibrants.py. This is validated.
     3276        '''
     3277        import ImageCalibrants as calFile
     3278        if calib in calFile.Calibrants.keys():
     3279            self.data['Image Controls']['calibrant'] = calib
     3280            return
     3281        print('Calibrant {} is not valid. Valid calibrants'.format(calib))
     3282        for i in calFile.Calibrants.keys():
     3283            if i: print('\t"{}"'.format(i))
     3284       
    32083285    def setControlFile(self,typ,imageRef,mult=None):
    32093286        '''Set a image to be used as a background/dark/gain map image
     
    32123289           'background image', 'dark image', 'gain map'; N.B. only the first
    32133290           four characters must be specified and case is ignored.
    3214         :param imageRef:
    3215         :param float mult:
     3291        :param imageRef: A reference to the desired image. Either the Image
     3292          tree name (str), the image's index (int) or
     3293          a image object (:class:`G2Image`)
     3294        :param float mult: a multiplier to be applied to the image (not used
     3295          for 'Gain map'; required for 'background image', 'dark image'
    32163296        '''
    3217 #        'image': ['background image', 'dark image', 'Gain map'],
    32183297        if 'back' in typ.lower():
    32193298            key = 'background image'
     
    32373316    def loadControls(self,filename):
    32383317        '''load controls from a .imctrl file
     3318
    32393319        :param str filename: specifies a file to be read, which should end
    32403320          with .imctrl
     
    32483328    def saveControls(self,filename):
    32493329        '''write current controls values to a .imctrl file
     3330
    32503331        :param str filename: specifies a file to write, which should end
    32513332          with .imctrl
     
    32543335        print('file {} written from {}'.format(filename,self.name))
    32553336
     3337    def loadMasks(self,filename,ignoreThreshold=False):
     3338        '''load masks from a .immask file
     3339
     3340        :param str filename: specifies a file to be read, which should end
     3341          with .immask
     3342        :param bool ignoreThreshold: If True, masks are loaded with
     3343          threshold masks. Default is False which means any Thresholds
     3344          in the file are ignored.
     3345        '''
     3346        G2fil.readMasks(filename,self.data['Masks'],ignoreThreshold)
     3347        print('file {} read into {}'.format(filename,self.name))
     3348       
     3349    def Recalibrate(self):
     3350        ImageZ = GetCorrImage(Readers['Image'],self.proj,self)
     3351        G2img.ImageRecalibrate(None,ImageZ,self.data['Image Controls'],self.data['Masks'])
     3352       
    32563353##########################
    32573354# Command Line Interface #
Note: See TracChangeset for help on using the changeset viewer.