source: trunk/imports/G2img_PILTIF.py @ 4918

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

add mechanism for posting a notice when G2 versions are updated

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 5.6 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2021-06-03 01:49:00 +0000 (Thu, 03 Jun 2021) $
4# $Author: toby $
5# $Revision: 4918 $
6# $URL: trunk/imports/G2img_PILTIF.py $
7# $Id: G2img_PILTIF.py 4918 2021-06-03 01:49:00Z 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.. Next command allows \\AA to be used in HTML
30
31.. only:: html
32
33   :math:`\\require{mediawiki-texvc}`
34
35.. tabularcolumns:: |l|p{4.5in}|
36
37==============================  ====================================================
38  keyword                        explanation
39==============================  ====================================================
40wavelength                       Wavelength in :math:`\\AA`
41distance                         Distance to sample in mm
42polarization                     Percentage polarized in horizontal plane
43sampleChangerCoordinate          Used for sample changers to track sample
44pixelSizeX                       Pixel size in X direction (microns)
45pixelSizeY                       Pixel size in Y direction (microns)
46CenterPixelX                     Location of beam center as a pixel number (in X)
47CenterPixelY                     Location of beam center as a pixel number (in X)
48==============================  ====================================================
49
50'''
51
52from __future__ import division, print_function
53import struct as st
54import numpy as np
55import time
56import GSASIIobj as G2obj
57import GSASIIpath
58import GSASIIfiles as G2fil
59import G2img_1TIF
60DEBUG = False
61GSASIIpath.SetVersionNumber("$Revision: 4918 $")
62
63class TIF_LibraryReader(G2obj.ImportImage):
64    '''Reads TIF files using a standard library routine. Metadata (such as pixel
65    size) must be specified by user, either in GUI or via a metadata file.
66    The library TIF reader can handle compression and other things that are not
67    commonly used at beamlines.
68    '''
69    def __init__(self):
70        super(self.__class__,self).__init__( # fancy way to self-reference
71            extensionlist=('.tif','.tiff'),
72            strictExtension=True,
73            formatName = 'Standard TIF image; metadata req.',
74            longFormatName = 'TIFF images read with standard library (metadata must be supplied)'
75            )
76        self.scriptable = True
77
78    def ContentsValidator(self, filename):
79        '''Does the header match the required TIF header?
80        '''
81        return G2img_1TIF.TIFValidator(filename)
82   
83    def Reader(self,filename, ParentFrame=None, **unused):
84        '''Read the TIF file using the PIL/Pillow reader and give the
85        user a chance to edit the likely wrong default image parameters.
86        '''
87        import PIL.Image as PI
88        self.Image = PI.open(filename,mode='r')
89        self.Npix = self.Image.size
90        if ParentFrame:
91            self.SciPy = True
92            self.Comments = ['no metadata']
93            self.Data = {'wavelength': 0.1, 'pixelSize': [200., 200.], 'distance': 100.0}
94            self.Data['size'] = list(self.Image.size)
95            self.Data['center'] = [int(i/2) for i in self.Image.size]
96            try:
97                Meta = open(filename+'.metadata','r')
98                head = Meta.readlines()
99                for line in head:
100                    line = line.strip()
101                    try:
102                        if '=' not in line: continue
103                        keyword = line.split('=')[0].strip()
104                        if 'wavelength' == keyword.lower():
105                            self.Data['wavelength'] = float(line.split('=')[1])
106                        elif 'distance' == keyword.lower():
107                            self.Data['distance'] = float(line.split('=')[1])
108                        elif 'polarization' == keyword.lower():
109                            polarization = float(line.split('=')[1])
110                            self.Data['PolaVal'] = [polarization,False]
111                        elif 'samplechangercoordinate' == keyword.lower():
112                            self.Data['samplechangerpos'] = float(line.split('=')[1])
113                        elif 'pixelsizex' == keyword.lower():
114                            self.Data['pixelSize'][0] = float(line.split('=')[1])
115                        elif 'pixelsizey' == keyword.lower():
116                            self.Data['pixelSize'][1] = float(line.split('=')[1])
117                        elif 'centerpixelx' == keyword.lower():
118                            self.Data['center'][0] = float(line.split('=')[1])
119                        elif 'centerpixely' == keyword.lower():
120                            self.Data['center'][1] = float(line.split('=')[1])
121                    except:
122                        G2fil.G2Print('error reading metadata: '+line)
123                Meta.close()
124                self.SciPy = False
125            except IOError:
126                G2fil.G2Print ('no metadata file found - image params must be set manually')
127                head = ['no metadata file found',]
128        if self.Npix == 0:
129            return False
130        self.LoadImage(ParentFrame,filename)
131        return True
Note: See TracBrowser for help on using the repository browser.