Changeset 2042 for trunk/GSASIIIO.py


Ignore:
Timestamp:
Nov 10, 2015 9:52:54 PM (6 years ago)
Author:
toby
Message:

move TIF code; correct bug; get rid of old GetImageData?, next step in migration to new import image code

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIIO.py

    r2041 r2042  
    363363    '''
    364364    # determine which formats are compatible with this file
    365     print 'Debug: using ReadImageData'
    366365    primaryReaders = []
    367366    secondaryReaders = []
     
    418417        print('Error reading file '+filename)
    419418        print('Error messages(s)\n'+errorReport)
    420         raise Exception('No image read')
    421    
     419        raise Exception('No image read')   
    422420def GetImageData(G2frame,imagefile,imageOnly=False):
    423     '''Read an image with the file reader keyed by the
    424     file extension.
    425 
    426     This routine will be replaced by ReadImageData, which will be renamed to this.
    427 
    428     :param wx.Frame G2frame: main GSAS-II Frame and data object.
    429 
    430     :param str imagefile: name of image file
    431 
    432     :param bool imageOnly: If True return only the image,
    433       otherwise  (default) return more (see below)
    434 
    435     :returns: an image as a numpy array or a list of four items:
    436       Comments, Data, Npix and the Image, as selected by imageOnly
    437 
    438     '''
    439     if GSASIIpath.GetConfigValue('debug'):  # test out using replacement routine
    440         return ReadImageData(G2frame,imagefile,imageOnly)
    441    
    442     ext = ospath.splitext(imagefile)[1]
    443     Comments = []
    444     Image = None
    445     if ext == '.tif' or ext == '.tiff':
    446         Comments,Data,Npix,Image = GetTifData(imagefile)
    447         if Npix == 0:
    448             print("GetTifData failed to read "+str(imagefile)+" Trying PIL")
    449             import scipy.misc
    450             Image = scipy.misc.imread(imagefile,flatten=True)
    451             Npix = Image.size
    452             Comments = ['no metadata']
    453             Data = {'wavelength': 0.1, 'pixelSize': [200, 200], 'distance': 100.0}
    454             Data['size'] = list(Image.shape)
    455             Data['center'] = [int(i/2) for i in Image.shape]
    456             if not imageOnly:
    457                 EditImageParms(G2frame,Data,Comments,Image,imagefile)
    458     elif ext == '.edf':
    459         Comments,Data,Npix,Image = GetEdfData(imagefile)
    460     elif ext == '.img':
    461         Comments,Data,Npix,Image = GetImgData(imagefile)
    462         Image[0][0] = 0
    463     elif ext in ['.mar3450','.mar2300','.mar2560']:
    464         Comments,Data,Npix,Image = GetMAR345Data(imagefile)
    465     elif ext in ['.sum','.avg','.cor'] or 'ge' in ext:
    466         Comments,Data,Npix,Image = GetGEsumData(imagefile)
    467     elif ext == '.G2img':
    468         Comments,Data,Npix,Image = GetG2Image(imagefile)
    469     elif ext == '.png':
    470         Comments,Data,Npix,Image = GetPNGData(imagefile)
    471         if not imageOnly:
    472             EditImageParms(G2frame,Data,Comments,Image,imagefile)
    473     elif ext == '.stl':
    474         Comments,Data,Npix,Image = GetRigaku(imagefile)
    475 #        if not imageOnly:
    476 #            EditImageParms(G2frame,Data,Comments,Image,imagefile)
    477     else:
    478         print 'Extension for file '+imagefile+' not recognized'
    479     if Image is None:
    480         raise Exception('No image read')
    481     if imageOnly:
    482         if TRANSP:
    483             print 'Transposing Image!'
    484             return Image.T
    485         else:
    486             return Image
    487     else:
    488         if TRANSP:
    489             print 'Transposing Image!'
    490             return Comments,Data,Npix,Image.T
    491         else:
    492             return Comments,Data,Npix,Image
     421    return ReadImageData(G2frame,imagefile,imageOnly)
    493422       
    494423def PutG2Image(filename,Comments,Data,Npix,image):
     
    766695        return Comments,Data,Npix,Image.T
    767696
    768 def GetTifData(filename,imageOnly=False):
    769     '''Read an image in a pseudo-tif format,
    770     as produced by a wide variety of software, almost always
    771     incorrectly in some way.
    772     '''
    773     import struct as st
    774     try:
    775         import Image as Im
    776     except ImportError:
    777         try:
    778             from PIL import Image as Im
    779         except ImportError:
    780             print "PIL/pillow Image module not present. TIFs cannot be read without this"
    781             raise Exception("PIL/pillow Image module not found")
    782     import array as ar
    783     import ReadMarCCDFrame as rmf
    784     File = open(filename,'rb')
    785     dataType = 5
    786     center = [None,None]
    787     wavelength = None
    788     distance = None
    789     try:
    790         Meta = open(filename+'.metadata','Ur')
    791         head = Meta.readlines()
    792         for line in head:
    793             line = line.strip()
    794             if 'dataType=' in line:
    795                 dataType = int(line.split('=')[1])
    796         Meta.close()
    797     except IOError:
    798         print 'no metadata file found - will try to read file anyway'
    799         head = ['no metadata file found',]
    800        
    801     tag = File.read(2)
    802     byteOrd = '<'
    803     if tag == 'II' and int(st.unpack('<h',File.read(2))[0]) == 42:     #little endian
    804         IFD = int(st.unpack(byteOrd+'i',File.read(4))[0])
    805     elif tag == 'MM' and int(st.unpack('>h',File.read(2))[0]) == 42:   #big endian
    806         byteOrd = '>'
    807         IFD = int(st.unpack(byteOrd+'i',File.read(4))[0])       
    808     else:
    809         lines = ['not a detector tiff file',]
    810         return lines,0,0,0
    811     File.seek(IFD)                                                  #get number of directory entries
    812     NED = int(st.unpack(byteOrd+'h',File.read(2))[0])
    813     IFD = {}
    814     nSlice = 1
    815     for ied in range(NED):
    816         Tag,Type = st.unpack(byteOrd+'Hh',File.read(4))
    817         nVal = st.unpack(byteOrd+'i',File.read(4))[0]
    818         if DEBUG: print 'Try:',Tag,Type,nVal
    819         if Type == 1:
    820             Value = st.unpack(byteOrd+nVal*'b',File.read(nVal))
    821         elif Type == 2:
    822             Value = st.unpack(byteOrd+'i',File.read(4))
    823         elif Type == 3:
    824             Value = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
    825             x = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
    826         elif Type == 4:
    827             if Tag in [273,279]:
    828                 nSlice = nVal
    829                 nVal = 1
    830             Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
    831         elif Type == 5:
    832             Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
    833         elif Type == 11:
    834             Value = st.unpack(byteOrd+nVal*'f',File.read(nVal*4))
    835         IFD[Tag] = [Type,nVal,Value]
    836         if DEBUG: print Tag,IFD[Tag]
    837     sizexy = [IFD[256][2][0],IFD[257][2][0]]
    838     [nx,ny] = sizexy
    839     Npix = nx*ny
    840     if 34710 in IFD:
    841         if not imageOnly:
    842             print 'Read MAR CCD tiff file: ',filename
    843         marFrame = rmf.marFrame(File,byteOrd,IFD)
    844         image = np.flipud(np.array(np.asarray(marFrame.image),dtype=np.int32))
    845         tifType = marFrame.filetitle
    846         pixy = [marFrame.pixelsizeX/1000.0,marFrame.pixelsizeY/1000.0]
    847         head = marFrame.outputHead()
    848 # extract resonable wavelength from header
    849         wavelength = marFrame.sourceWavelength*1e-5
    850         wavelength = (marFrame.opticsWavelength > 0) and marFrame.opticsWavelength*1e-5 or wavelength
    851         wavelength = (wavelength <= 0) and None or wavelength
    852 # extract resonable distance from header
    853         distance = (marFrame.startXtalToDetector+marFrame.endXtalToDetector)*5e-4
    854         distance = (distance <= 0) and marFrame.xtalToDetector*1e-3 or distance
    855         distance = (distance <= 0) and None or distance
    856 # extract resonable center from header
    857         center = [marFrame.beamX*marFrame.pixelsizeX*1e-9,marFrame.beamY*marFrame.pixelsizeY*1e-9]
    858         center = (center[0] != 0 and center[1] != 0) and center or [None,None]
    859 #print head,tifType,pixy
    860     elif nSlice > 1:    #CheMin multislice tif file!
    861         tifType = 'CheMin'
    862         pixy = [40,40]
    863         image = np.flipud(np.array(Im.open(filename)))*10.
    864         distance = 18.0
    865         center = [pixy[0]*sizexy[0]/2000,0]     #the CheMin beam stop is here
    866         wavelength = 1.78892
    867     elif 272 in IFD:
    868         ifd = IFD[272]
    869         File.seek(ifd[2][0])
    870         S = File.read(ifd[1])
    871         if 'PILATUS' in S:
    872             tifType = 'Pilatus'
    873             dataType = 0
    874             pixy = [172,172]
    875             File.seek(4096)
    876             if not imageOnly:
    877                 print 'Read Pilatus tiff file: ',filename
    878             image = ar.array('L',File.read(4*Npix))
    879             image = np.array(np.asarray(image),dtype=np.int32)
    880         else:
    881             if IFD[258][2][0] == 16:
    882                 tifType = 'GE'
    883                 pixy = [200,200]
    884                 File.seek(8)
    885                 if not imageOnly:
    886                     print 'Read GE-detector tiff file: ',filename
    887                 image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    888             elif IFD[258][2][0] == 32:
    889                 tifType = 'CHESS'
    890                 pixy = [200,200]
    891                 File.seek(8)
    892                 if not imageOnly:
    893                     print 'Read CHESS-detector tiff file: ',filename
    894                 image = np.array(ar.array('L',File.read(4*Npix)),dtype=np.int32)
    895            
    896     elif 262 in IFD and IFD[262][2][0] > 4:
    897         tifType = 'DND'
    898         pixy = [158,158]
    899         File.seek(512)
    900         if not imageOnly:
    901             print 'Read DND SAX/WAX-detector tiff file: ',filename
    902         image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    903     elif sizexy == [1536,1536]:
    904         tifType = 'APS Gold'
    905         pixy = [150,150]
    906         File.seek(64)
    907         if not imageOnly:
    908             print 'Read Gold tiff file:',filename
    909         image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    910     elif sizexy == [2048,2048] or sizexy == [1024,1024] or sizexy == [3072,3072]:
    911         if IFD[273][2][0] == 8:
    912             if IFD[258][2][0] == 32:
    913                 tifType = 'PE'
    914                 pixy = [200,200]
    915                 File.seek(8)
    916                 if not imageOnly:
    917                     print 'Read APS PE-detector tiff file: ',filename
    918                 if dataType == 5:
    919                     image = np.array(ar.array('f',File.read(4*Npix)),dtype=np.float32)
    920                 else:
    921                     image = np.array(ar.array('I',File.read(4*Npix)),dtype=np.int32)
    922             elif IFD[258][2][0] == 16:
    923                 tifType = 'MedOptics D1'
    924                 pixy = [46.9,46.9]
    925                 File.seek(8)
    926                 if not imageOnly:
    927                     print 'Read MedOptics D1 tiff file: ',filename
    928                 image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    929                  
    930         elif IFD[273][2][0] == 4096:
    931             if sizexy[0] == 3072:
    932                 pixy =  [73,73]
    933                 tifType = 'MAR225'           
    934             else:
    935                 pixy = [158,158]
    936                 tifType = 'MAR325'           
    937             File.seek(4096)
    938             if not imageOnly:
    939                 print 'Read MAR CCD tiff file: ',filename
    940             image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    941         elif IFD[273][2][0] == 512:
    942             tiftype = '11-ID-C'
    943             pixy = [200,200]
    944             File.seek(512)
    945             if not imageOnly:
    946                 print 'Read 11-ID-C tiff file: ',filename
    947             image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    948         elif IFD[273][2][0] == 168:
    949             tifType = 'ImageJ'
    950             dataType = 0
    951             pixy = [200,200]
    952             File.seek(IFD[273][2][0])
    953             if not imageOnly:
    954                 print 'Read ImageJ tiff file: ',filename
    955             image = ar.array('H',File.read(2*Npix))
    956             if '>' in byteOrd:
    957                 image.byteswap()
    958             image = np.array(np.asarray(image,dtype='H'),dtype=np.int32)           
    959                    
    960     elif sizexy == [4096,4096]:
    961         if IFD[273][2][0] == 8:
    962             if IFD[258][2][0] == 16:
    963                 tifType = 'scanCCD'
    964                 pixy = [9,9]
    965                 File.seek(8)
    966                 if not imageOnly:
    967                     print 'Read APS scanCCD tiff file: ',filename
    968                 image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    969         elif IFD[273][2][0] == 4096:
    970             tifType = 'Rayonix'
    971             pixy = [73.242,73.242]
    972             File.seek(4096)
    973             if not imageOnly:
    974                 print 'Read Rayonix MX300HE tiff file: ',filename
    975             image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    976 #    elif sizexy == [960,960]:
    977 #        tiftype = 'PE-BE'
    978 #        pixy = (200,200)
    979 #        File.seek(8)
    980 #        if not imageOnly:
    981 #            print 'Read Gold tiff file:',filename
    982 #        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    983            
    984     else:
    985         lines = ['not a known detector tiff file',]
    986         return lines,0,0,0
    987 
    988     if sizexy[1]*sizexy[0] != image.size: # test is resize is allowed
    989         lines = ['not a known detector tiff file',]
    990         return lines,0,0,0
    991        
    992     image = np.reshape(image,(sizexy[1],sizexy[0]))
    993     center = (not center[0]) and [pixy[0]*sizexy[0]/2000,pixy[1]*sizexy[1]/2000] or center
    994     wavelength = (not wavelength) and 0.10 or wavelength
    995     distance = (not distance) and 100.0 or distance
    996     data = {'pixelSize':pixy,'wavelength':wavelength,'distance':distance,'center':center,'size':sizexy}
    997     File.close()   
    998     if imageOnly:
    999         return image
    1000     else:
    1001         return head,data,Npix,image
    1002697   
    1003698#def GetTifData(filename,imageOnly=False):
Note: See TracChangeset for help on using the changeset viewer.