source: trunk/imports/G2img_PILTIF.py @ 4917

Last change on this file since 4917 was 4917, checked in by toby, 5 months ago

split G2 & pillow readers for TIF; document

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 5.5 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2021-05-29 03:20:46 +0000 (Sat, 29 May 2021) $
4# $Author: toby $
5# $Revision: 4917 $
6# $URL: trunk/imports/G2img_PILTIF.py $
7# $Id: G2img_PILTIF.py 4917 2021-05-29 03:20:46Z toby $
8########### SVN repository information ###################
9'''
10*Module G2img_PILTIF: Std Tagged-image File images*
11-----------------------------------------------------
12
13Routine to read an image in Tagged-image file (TIF) format using a standard
14image library function. This means that parameters such as the pixel size
15(which is in the TIFF header but is almost never correct)
16and distance to sample, etc. are not correct unless specified in a
17separate metadata file.
18
19The metadata can be specified in a file with the same name and path as
20the TIFF file except that the the extension is .metadata.
21
22The contents of that file are a series of lines of form::
23
24     keyword = value
25
26Note that capitalization of keywords is ignored. Defined keywords are in table below. Any line
27without one of these keywords will be ignored.
28
29.. tabularcolumns:: |l|p{4.5in}|
30
31==============================  ====================================================
32  keyword                        explanation
33==============================  ====================================================
34wavelength                       Wavelength in :math:`\\AA`
35distance                         Distance to sample in mm
36polarization                     Percentage polarized in horizontal plane
37sampleChangerCoordinate          Used for sample changers to track sample
38pixelSizeX                       Pixel size in X direction (microns)
39pixelSizeY                       Pixel size in Y direction (microns)
40CenterPixelX                     Location of beam center as a pixel number (in X)
41CenterPixelY                     Location of beam center as a pixel number (in X)
42==============================  ====================================================
43
44'''
45
46from __future__ import division, print_function
47import struct as st
48import numpy as np
49import time
50import GSASIIobj as G2obj
51import GSASIIpath
52import GSASIIfiles as G2fil
53import G2img_1TIF
54DEBUG = False
55GSASIIpath.SetVersionNumber("$Revision: 4917 $")
56
57class TIF_LibraryReader(G2obj.ImportImage):
58    '''Reads TIF files using a standard library routine. Metadata (such as pixel
59    size) must be specified by user, either in GUI or via a metadata file.
60    The library TIF reader can handle compression and other things that are not
61    commonly used at beamlines.
62    '''
63    def __init__(self):
64        super(self.__class__,self).__init__( # fancy way to self-reference
65            extensionlist=('.tif','.tiff'),
66            strictExtension=True,
67            formatName = 'Standard TIF image; metadata req.',
68            longFormatName = 'TIFF images read with standard library (metadata must be supplied)'
69            )
70        self.scriptable = True
71
72    def ContentsValidator(self, filename):
73        '''Does the header match the required TIF header?
74        '''
75        return G2img_1TIF.TIFValidator(filename)
76   
77    def Reader(self,filename, ParentFrame=None, **unused):
78        '''Read the TIF file using the PIL/Pillow reader and give the
79        user a chance to edit the likely wrong default image parameters.
80        '''
81        import PIL.Image as PI
82        self.Image = PI.open(filename,mode='r')
83        self.Npix = self.Image.size
84        if ParentFrame:
85            self.SciPy = True
86            self.Comments = ['no metadata']
87            self.Data = {'wavelength': 0.1, 'pixelSize': [200., 200.], 'distance': 100.0}
88            self.Data['size'] = list(self.Image.size)
89            self.Data['center'] = [int(i/2) for i in self.Image.size]
90            try:
91                Meta = open(filename+'.metadata','r')
92                head = Meta.readlines()
93                for line in head:
94                    line = line.strip()
95                    try:
96                        if '=' not in line: continue
97                        keyword = line.split('=')[0].strip()
98                        if 'wavelength' == keyword.lower():
99                            self.Data['wavelength'] = float(line.split('=')[1])
100                        elif 'distance' == keyword.lower():
101                            self.Data['distance'] = float(line.split('=')[1])
102                        elif 'polarization' == keyword.lower():
103                            polarization = float(line.split('=')[1])
104                            self.Data['PolaVal'] = [polarization,False]
105                        elif 'samplechangercoordinate' == keyword.lower():
106                            self.Data['samplechangerpos'] = float(line.split('=')[1])
107                        elif 'pixelsizex' == keyword.lower():
108                            self.Data['pixelSize'][0] = float(line.split('=')[1])
109                        elif 'pixelsizey' == keyword.lower():
110                            self.Data['pixelSize'][1] = float(line.split('=')[1])
111                        elif 'centerpixelx' == keyword.lower():
112                            self.Data['center'][0] = float(line.split('=')[1])
113                        elif 'centerpixely' == keyword.lower():
114                            self.Data['center'][1] = float(line.split('=')[1])
115                    except:
116                        G2fil.G2Print('error reading metadata: '+line)
117                Meta.close()
118                self.SciPy = False
119            except IOError:
120                G2fil.G2Print ('no metadata file found - image params must be set manually')
121                head = ['no metadata file found',]
122        if self.Npix == 0:
123            return False
124        self.LoadImage(ParentFrame,filename)
125        return True
Note: See TracBrowser for help on using the repository browser.