Changeset 3815
- Timestamp:
- Feb 11, 2019 11:26:52 AM (4 years ago)
- Location:
- trunk
- Files:
-
- 4 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIfiles.py
r3814 r3815 743 743 File.write(key+':'+str(data[key])+'\n') 744 744 File.close() 745 745 746 def 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 802 def 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 540 540 return tam.T 541 541 542 def ImageRecalibrate(G2frame, data,masks):542 def ImageRecalibrate(G2frame,ImageZ,data,masks): 543 543 '''Called to repeat the calibration on an image, usually called after 544 544 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 545 551 ''' 546 552 import ImageCalibrants as calFile … … 580 586 wave = data['wavelength'] 581 587 frame = masks['Frames'] 582 tam = ma.make_mask_none( G2frame.ImageZ.shape)588 tam = ma.make_mask_none(ImageZ.shape) 583 589 if frame: 584 590 tam = ma.mask_or(tam,MakeFrameMask(data,frame)) … … 591 597 break 592 598 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] 594 600 if Ring: 595 601 if iH >= skip: … … 621 627 data['ellipses'].append(copy.deepcopy(ellipse+('b',))) 622 628 print ('calibration time = %.3f'%(time.time()-time0)) 623 G2plt.PlotImage(G2frame,newImage=True) 629 if G2frame: 630 G2plt.PlotImage(G2frame,newImage=True) 624 631 return [vals,varyList,sigList,parmDict] 625 632 -
trunk/GSASIIimgGUI.py
r3814 r3815 192 192 193 193 def OnRecalibrate(event): 194 G2img.ImageRecalibrate(G2frame, data,masks)194 G2img.ImageRecalibrate(G2frame,G2frame.ImageZ,data,masks) 195 195 wx.CallLater(100,UpdateImageControls,G2frame,data,masks) 196 196 … … 217 217 Mid = G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Masks') 218 218 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) 220 221 sigList = list(sigList) 221 222 if 'dist' not in varyList: … … 1436 1437 if dlg.ShowModal() == wx.ID_OK: 1437 1438 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) 1459 1440 wx.CallAfter(UpdateMasks,G2frame,data) 1460 1441 G2plt.PlotExposedImage(G2frame,event=event) -
trunk/GSASIIscriptable.py
r3814 r3815 576 576 import GSASIIElem as G2elem 577 577 import GSASIIfiles as G2fil 578 import GSASIIimage as G2img 578 579 579 580 # Delay imports to not slow down small scripts that don't need them … … 584 585 585 586 def LoadG2fil(): 586 """ Delay importing this module, it is slow"""587 """Setup GSAS-II importers. Delay importing this module, it is slow""" 587 588 if len(Readers['Pwdr']) > 0: return 588 589 # initialize imports … … 1160 1161 into[:] = from_ 1161 1162 1163 def 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') 1162 1224 1163 1225 class G2ObjectWrapper(object): … … 3123 3185 'DetDepthRef', 'showLines'], 3124 3186 'str': ['SampleShape', 'binType', 'formatName', 'color', 3125 'type', 'calibrant'],3187 'type', ], 3126 3188 'list': ['GonioAngles', 'IOtth', 'LRazimuth', 'Oblique', 'PolaVal', 3127 3189 'SampleAbs', 'center', 'ellipses', 'linescan', 3128 3190 'pixelSize', 'range', 'ring', 'rings', 'size', ], 3129 3191 'dict': ['varylist'], 3130 # 'image': ['background image', 'dark image', 'Gain map'],3131 3192 } 3132 3193 '''Defines the items known to exist in the Image Controls tree section 3133 3194 and their data types. 3134 3195 ''' 3196 # special handling: 'background image', 'dark image', 'Gain map', 3197 # 'calibrant' 3135 3198 3136 3199 def __init__(self, data, name, proj): … … 3206 3269 return matchList 3207 3270 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 3208 3285 def setControlFile(self,typ,imageRef,mult=None): 3209 3286 '''Set a image to be used as a background/dark/gain map image … … 3212 3289 'background image', 'dark image', 'gain map'; N.B. only the first 3213 3290 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' 3216 3296 ''' 3217 # 'image': ['background image', 'dark image', 'Gain map'],3218 3297 if 'back' in typ.lower(): 3219 3298 key = 'background image' … … 3237 3316 def loadControls(self,filename): 3238 3317 '''load controls from a .imctrl file 3318 3239 3319 :param str filename: specifies a file to be read, which should end 3240 3320 with .imctrl … … 3248 3328 def saveControls(self,filename): 3249 3329 '''write current controls values to a .imctrl file 3330 3250 3331 :param str filename: specifies a file to write, which should end 3251 3332 with .imctrl … … 3254 3335 print('file {} written from {}'.format(filename,self.name)) 3255 3336 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 3256 3353 ########################## 3257 3354 # Command Line Interface #
Note: See TracChangeset
for help on using the changeset viewer.