pylibtiff-0.3.0~svn78/0000775000175100017510000000000011660704745013630 5ustar tilletillepylibtiff-0.3.0~svn78/README.txt0000664000175100017510000000310611370362345015320 0ustar tilletille ================================= PyLibTiff - a Python tiff library ================================= :Authors: Pearu Peterson :Website: http://pylibtiff.googlecode.com/ :License: New BSD License History ======= * Started numpy.memmap wrapper of tiff files in April 2010. * Project published on April 22, 2009. Download ======== The latest release can be downloaded from pylibtiff website. The latest development code is available via SVN. To check it out, run:: svn checkout http://pylibtiff.googlecode.com/svn/trunk/ pylibtiff-svn cd pylibtiff-svn Installation ============ To use pylibtiff, the following is required: * Python 2.5 or newer * libtiff library * nose for running pylibtiff tests To install pylibtiff, unpack the archive file, change to the pylibtiff source directory ``pylibtiff-?.?*`` (that contains setup.py file and pylibtiff module), and run:: python setup.py install Testing ======= To test pure Python pylibtiff from source directory, run:: nosetests libtiff/tests/ Basic usage =========== Import pylibtiff with >>> from libtiff import * that will provide a class TIFF to hold a tiff file: >>> tiff = TIFF.open('filename') >>> image = tiff.read_image() The TIFF class provides ctypes based wrapper to the C libtiff library. Additional documentation is available online in Pylibtiff website. Help and bug reports ==================== You can report bugs at the pylibtiff issue tracker: http://code.google.com/p/pylibtiff/issues/list Any comments and questions can be sent also to the authors. pylibtiff-0.3.0~svn78/libtiff/0000775000175100017510000000000011660704745015247 5ustar tilletillepylibtiff-0.3.0~svn78/libtiff/tiff_h_3_8_2.py0000664000175100017510000002573211370362345017755 0ustar tilletilleTIFF_VERSION = 42 TIFF_BIGTIFF_VERSION = 43 TIFF_BIGENDIAN = 0x4d4d TIFF_LITTLEENDIAN = 0x4949 MDI_LITTLEENDIAN = 0x5045 MDI_BIGENDIAN = 0x4550 TIFF_MAGIC_SIZE = 2 TIFF_VERSION_SIZE = 2 TIFF_DIROFFSET_SIZE = 4 TIFFTAG_SUBFILETYPE = 254 FILETYPE_REDUCEDIMAGE = 0x1 FILETYPE_PAGE = 0x2 FILETYPE_MASK = 0x4 TIFFTAG_OSUBFILETYPE = 255 OFILETYPE_IMAGE = 1 OFILETYPE_REDUCEDIMAGE = 2 OFILETYPE_PAGE = 3 TIFFTAG_IMAGEWIDTH = 256 TIFFTAG_IMAGELENGTH = 257 TIFFTAG_BITSPERSAMPLE = 258 TIFFTAG_COMPRESSION = 259 COMPRESSION_NONE = 1 COMPRESSION_CCITTRLE = 2 COMPRESSION_CCITTFAX3 = 3 COMPRESSION_CCITT_T4 = 3 COMPRESSION_CCITTFAX4 = 4 COMPRESSION_CCITT_T6 = 4 COMPRESSION_LZW = 5 COMPRESSION_OJPEG = 6 COMPRESSION_JPEG = 7 COMPRESSION_NEXT = 32766 COMPRESSION_CCITTRLEW = 32771 COMPRESSION_PACKBITS = 32773 COMPRESSION_THUNDERSCAN = 32809 COMPRESSION_IT8CTPAD = 32895 COMPRESSION_IT8LW = 32896 COMPRESSION_IT8MP = 32897 COMPRESSION_IT8BL = 32898 COMPRESSION_PIXARFILM = 32908 COMPRESSION_PIXARLOG = 32909 COMPRESSION_DEFLATE = 32946 COMPRESSION_ADOBE_DEFLATE = 8 COMPRESSION_DCS = 32947 COMPRESSION_JBIG = 34661 COMPRESSION_SGILOG = 34676 COMPRESSION_SGILOG24 = 34677 COMPRESSION_JP2000 = 34712 TIFFTAG_PHOTOMETRIC = 262 PHOTOMETRIC_MINISWHITE = 0 PHOTOMETRIC_MINISBLACK = 1 PHOTOMETRIC_RGB = 2 PHOTOMETRIC_PALETTE = 3 PHOTOMETRIC_MASK = 4 PHOTOMETRIC_SEPARATED = 5 PHOTOMETRIC_YCBCR = 6 PHOTOMETRIC_CIELAB = 8 PHOTOMETRIC_ICCLAB = 9 PHOTOMETRIC_ITULAB = 10 PHOTOMETRIC_LOGL = 32844 PHOTOMETRIC_LOGLUV = 32845 TIFFTAG_THRESHHOLDING = 263 THRESHHOLD_BILEVEL = 1 THRESHHOLD_HALFTONE = 2 THRESHHOLD_ERRORDIFFUSE = 3 TIFFTAG_CELLWIDTH = 264 TIFFTAG_CELLLENGTH = 265 TIFFTAG_FILLORDER = 266 FILLORDER_MSB2LSB = 1 FILLORDER_LSB2MSB = 2 TIFFTAG_DOCUMENTNAME = 269 TIFFTAG_IMAGEDESCRIPTION = 270 TIFFTAG_MAKE = 271 TIFFTAG_MODEL = 272 TIFFTAG_STRIPOFFSETS = 273 TIFFTAG_ORIENTATION = 274 ORIENTATION_TOPLEFT = 1 ORIENTATION_TOPRIGHT = 2 ORIENTATION_BOTRIGHT = 3 ORIENTATION_BOTLEFT = 4 ORIENTATION_LEFTTOP = 5 ORIENTATION_RIGHTTOP = 6 ORIENTATION_RIGHTBOT = 7 ORIENTATION_LEFTBOT = 8 TIFFTAG_SAMPLESPERPIXEL = 277 TIFFTAG_ROWSPERSTRIP = 278 TIFFTAG_STRIPBYTECOUNTS = 279 TIFFTAG_MINSAMPLEVALUE = 280 TIFFTAG_MAXSAMPLEVALUE = 281 TIFFTAG_XRESOLUTION = 282 TIFFTAG_YRESOLUTION = 283 TIFFTAG_PLANARCONFIG = 284 PLANARCONFIG_CONTIG = 1 PLANARCONFIG_SEPARATE = 2 TIFFTAG_PAGENAME = 285 TIFFTAG_XPOSITION = 286 TIFFTAG_YPOSITION = 287 TIFFTAG_FREEOFFSETS = 288 TIFFTAG_FREEBYTECOUNTS = 289 TIFFTAG_GRAYRESPONSEUNIT = 290 GRAYRESPONSEUNIT_10S = 1 GRAYRESPONSEUNIT_100S = 2 GRAYRESPONSEUNIT_1000S = 3 GRAYRESPONSEUNIT_10000S = 4 GRAYRESPONSEUNIT_100000S = 5 TIFFTAG_GRAYRESPONSECURVE = 291 TIFFTAG_GROUP3OPTIONS = 292 TIFFTAG_T4OPTIONS = 292 GROUP3OPT_2DENCODING = 0x1 GROUP3OPT_UNCOMPRESSED = 0x2 GROUP3OPT_FILLBITS = 0x4 TIFFTAG_GROUP4OPTIONS = 293 TIFFTAG_T6OPTIONS = 293 GROUP4OPT_UNCOMPRESSED = 0x2 TIFFTAG_RESOLUTIONUNIT = 296 RESUNIT_NONE = 1 RESUNIT_INCH = 2 RESUNIT_CENTIMETER = 3 TIFFTAG_PAGENUMBER = 297 TIFFTAG_COLORRESPONSEUNIT = 300 COLORRESPONSEUNIT_10S = 1 COLORRESPONSEUNIT_100S = 2 COLORRESPONSEUNIT_1000S = 3 COLORRESPONSEUNIT_10000S = 4 COLORRESPONSEUNIT_100000S = 5 TIFFTAG_TRANSFERFUNCTION = 301 TIFFTAG_SOFTWARE = 305 TIFFTAG_DATETIME = 306 TIFFTAG_ARTIST = 315 TIFFTAG_HOSTCOMPUTER = 316 TIFFTAG_PREDICTOR = 317 PREDICTOR_NONE = 1 PREDICTOR_HORIZONTAL = 2 PREDICTOR_FLOATINGPOINT = 3 TIFFTAG_WHITEPOINT = 318 TIFFTAG_PRIMARYCHROMATICITIES = 319 TIFFTAG_COLORMAP = 320 TIFFTAG_HALFTONEHINTS = 321 TIFFTAG_TILEWIDTH = 322 TIFFTAG_TILELENGTH = 323 TIFFTAG_TILEOFFSETS = 324 TIFFTAG_TILEBYTECOUNTS = 325 TIFFTAG_BADFAXLINES = 326 TIFFTAG_CLEANFAXDATA = 327 CLEANFAXDATA_CLEAN = 0 CLEANFAXDATA_REGENERATED = 1 CLEANFAXDATA_UNCLEAN = 2 TIFFTAG_CONSECUTIVEBADFAXLINES = 328 TIFFTAG_SUBIFD = 330 TIFFTAG_INKSET = 332 INKSET_CMYK = 1 INKSET_MULTIINK = 2 TIFFTAG_INKNAMES = 333 TIFFTAG_NUMBEROFINKS = 334 TIFFTAG_DOTRANGE = 336 TIFFTAG_TARGETPRINTER = 337 TIFFTAG_EXTRASAMPLES = 338 EXTRASAMPLE_UNSPECIFIED = 0 EXTRASAMPLE_ASSOCALPHA = 1 EXTRASAMPLE_UNASSALPHA = 2 TIFFTAG_SAMPLEFORMAT = 339 SAMPLEFORMAT_UINT = 1 SAMPLEFORMAT_INT = 2 SAMPLEFORMAT_IEEEFP = 3 SAMPLEFORMAT_VOID = 4 SAMPLEFORMAT_COMPLEXINT = 5 SAMPLEFORMAT_COMPLEXIEEEFP = 6 TIFFTAG_SMINSAMPLEVALUE = 340 TIFFTAG_SMAXSAMPLEVALUE = 341 TIFFTAG_CLIPPATH = 343 TIFFTAG_XCLIPPATHUNITS = 344 TIFFTAG_YCLIPPATHUNITS = 345 TIFFTAG_INDEXED = 346 TIFFTAG_JPEGTABLES = 347 TIFFTAG_OPIPROXY = 351 TIFFTAG_JPEGPROC = 512 JPEGPROC_BASELINE = 1 JPEGPROC_LOSSLESS = 14 TIFFTAG_JPEGIFOFFSET = 513 TIFFTAG_JPEGIFBYTECOUNT = 514 TIFFTAG_JPEGRESTARTINTERVAL = 515 TIFFTAG_JPEGLOSSLESSPREDICTORS = 517 TIFFTAG_JPEGPOINTTRANSFORM = 518 TIFFTAG_JPEGQTABLES = 519 TIFFTAG_JPEGDCTABLES = 520 TIFFTAG_JPEGACTABLES = 521 TIFFTAG_YCBCRCOEFFICIENTS = 529 TIFFTAG_YCBCRSUBSAMPLING = 530 TIFFTAG_YCBCRPOSITIONING = 531 YCBCRPOSITION_CENTERED = 1 YCBCRPOSITION_COSITED = 2 TIFFTAG_REFERENCEBLACKWHITE = 532 TIFFTAG_XMLPACKET = 700 TIFFTAG_OPIIMAGEID = 32781 TIFFTAG_REFPTS = 32953 TIFFTAG_REGIONTACKPOINT = 32954 TIFFTAG_REGIONWARPCORNERS = 32955 TIFFTAG_REGIONAFFINE = 32956 TIFFTAG_MATTEING = 32995 TIFFTAG_DATATYPE = 32996 TIFFTAG_IMAGEDEPTH = 32997 TIFFTAG_TILEDEPTH = 32998 TIFFTAG_PIXAR_IMAGEFULLWIDTH = 33300 TIFFTAG_PIXAR_IMAGEFULLLENGTH = 33301 TIFFTAG_PIXAR_TEXTUREFORMAT = 33302 TIFFTAG_PIXAR_WRAPMODES = 33303 TIFFTAG_PIXAR_FOVCOT = 33304 TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN = 33305 TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA = 33306 TIFFTAG_WRITERSERIALNUMBER = 33405 TIFFTAG_COPYRIGHT = 33432 TIFFTAG_RICHTIFFIPTC = 33723 TIFFTAG_IT8SITE = 34016 TIFFTAG_IT8COLORSEQUENCE = 34017 TIFFTAG_IT8HEADER = 34018 TIFFTAG_IT8RASTERPADDING = 34019 TIFFTAG_IT8BITSPERRUNLENGTH = 34020 TIFFTAG_IT8BITSPEREXTENDEDRUNLENGTH = 34021 TIFFTAG_IT8COLORTABLE = 34022 TIFFTAG_IT8IMAGECOLORINDICATOR = 34023 TIFFTAG_IT8BKGCOLORINDICATOR = 34024 TIFFTAG_IT8IMAGECOLORVALUE = 34025 TIFFTAG_IT8BKGCOLORVALUE = 34026 TIFFTAG_IT8PIXELINTENSITYRANGE = 34027 TIFFTAG_IT8TRANSPARENCYINDICATOR = 34028 TIFFTAG_IT8COLORCHARACTERIZATION = 34029 TIFFTAG_IT8HCUSAGE = 34030 TIFFTAG_IT8TRAPINDICATOR = 34031 TIFFTAG_IT8CMYKEQUIVALENT = 34032 TIFFTAG_FRAMECOUNT = 34232 TIFFTAG_PHOTOSHOP = 34377 TIFFTAG_EXIFIFD = 34665 TIFFTAG_ICCPROFILE = 34675 TIFFTAG_JBIGOPTIONS = 34750 TIFFTAG_GPSIFD = 34853 TIFFTAG_FAXRECVPARAMS = 34908 TIFFTAG_FAXSUBADDRESS = 34909 TIFFTAG_FAXRECVTIME = 34910 TIFFTAG_FAXDCS = 34911 TIFFTAG_STONITS = 37439 TIFFTAG_FEDEX_EDR = 34929 TIFFTAG_INTEROPERABILITYIFD = 40965 TIFFTAG_DNGVERSION = 50706 TIFFTAG_DNGBACKWARDVERSION = 50707 TIFFTAG_UNIQUECAMERAMODEL = 50708 TIFFTAG_LOCALIZEDCAMERAMODEL = 50709 TIFFTAG_CFAPLANECOLOR = 50710 TIFFTAG_CFALAYOUT = 50711 TIFFTAG_LINEARIZATIONTABLE = 50712 TIFFTAG_BLACKLEVELREPEATDIM = 50713 TIFFTAG_BLACKLEVEL = 50714 TIFFTAG_BLACKLEVELDELTAH = 50715 TIFFTAG_BLACKLEVELDELTAV = 50716 TIFFTAG_WHITELEVEL = 50717 TIFFTAG_DEFAULTSCALE = 50718 TIFFTAG_DEFAULTCROPORIGIN = 50719 TIFFTAG_DEFAULTCROPSIZE = 50720 TIFFTAG_COLORMATRIX1 = 50721 TIFFTAG_COLORMATRIX2 = 50722 TIFFTAG_CAMERACALIBRATION1 = 50723 TIFFTAG_CAMERACALIBRATION2 = 50724 TIFFTAG_REDUCTIONMATRIX1 = 50725 TIFFTAG_REDUCTIONMATRIX2 = 50726 TIFFTAG_ANALOGBALANCE = 50727 TIFFTAG_ASSHOTNEUTRAL = 50728 TIFFTAG_ASSHOTWHITEXY = 50729 TIFFTAG_BASELINEEXPOSURE = 50730 TIFFTAG_BASELINENOISE = 50731 TIFFTAG_BASELINESHARPNESS = 50732 TIFFTAG_BAYERGREENSPLIT = 50733 TIFFTAG_LINEARRESPONSELIMIT = 50734 TIFFTAG_CAMERASERIALNUMBER = 50735 TIFFTAG_LENSINFO = 50736 TIFFTAG_CHROMABLURRADIUS = 50737 TIFFTAG_ANTIALIASSTRENGTH = 50738 TIFFTAG_SHADOWSCALE = 50739 TIFFTAG_DNGPRIVATEDATA = 50740 TIFFTAG_MAKERNOTESAFETY = 50741 TIFFTAG_CALIBRATIONILLUMINANT1 = 50778 TIFFTAG_CALIBRATIONILLUMINANT2 = 50779 TIFFTAG_BESTQUALITYSCALE = 50780 TIFFTAG_RAWDATAUNIQUEID = 50781 TIFFTAG_ORIGINALRAWFILENAME = 50827 TIFFTAG_ORIGINALRAWFILEDATA = 50828 TIFFTAG_ACTIVEAREA = 50829 TIFFTAG_MASKEDAREAS = 50830 TIFFTAG_ASSHOTICCPROFILE = 50831 TIFFTAG_ASSHOTPREPROFILEMATRIX = 50832 TIFFTAG_CURRENTICCPROFILE = 50833 TIFFTAG_CURRENTPREPROFILEMATRIX = 50834 TIFFTAG_DCSHUESHIFTVALUES = 65535 TIFFTAG_FAXMODE = 65536 FAXMODE_CLASSIC = 0x0000 FAXMODE_NORTC = 0x0001 FAXMODE_NOEOL = 0x0002 FAXMODE_BYTEALIGN = 0x0004 FAXMODE_WORDALIGN = 0x0008 FAXMODE_CLASSF = FAXMODE_NORTC TIFFTAG_JPEGQUALITY = 65537 TIFFTAG_JPEGCOLORMODE = 65538 JPEGCOLORMODE_RAW = 0x0000 JPEGCOLORMODE_RGB = 0x0001 TIFFTAG_JPEGTABLESMODE = 65539 JPEGTABLESMODE_QUANT = 0x0001 JPEGTABLESMODE_HUFF = 0x0002 TIFFTAG_FAXFILLFUNC = 65540 TIFFTAG_PIXARLOGDATAFMT = 65549 PIXARLOGDATAFMT_8BIT = 0 PIXARLOGDATAFMT_8BITABGR = 1 PIXARLOGDATAFMT_11BITLOG = 2 PIXARLOGDATAFMT_12BITPICIO = 3 PIXARLOGDATAFMT_16BIT = 4 PIXARLOGDATAFMT_FLOAT = 5 TIFFTAG_DCSIMAGERTYPE = 65550 DCSIMAGERMODEL_M3 = 0 DCSIMAGERMODEL_M5 = 1 DCSIMAGERMODEL_M6 = 2 DCSIMAGERFILTER_IR = 0 DCSIMAGERFILTER_MONO = 1 DCSIMAGERFILTER_CFA = 2 DCSIMAGERFILTER_OTHER = 3 TIFFTAG_DCSINTERPMODE = 65551 DCSINTERPMODE_NORMAL = 0x0 DCSINTERPMODE_PREVIEW = 0x1 TIFFTAG_DCSBALANCEARRAY = 65552 TIFFTAG_DCSCORRECTMATRIX = 65553 TIFFTAG_DCSGAMMA = 65554 TIFFTAG_DCSTOESHOULDERPTS = 65555 TIFFTAG_DCSCALIBRATIONFD = 65556 TIFFTAG_ZIPQUALITY = 65557 TIFFTAG_PIXARLOGQUALITY = 65558 TIFFTAG_DCSCLIPRECTANGLE = 65559 TIFFTAG_SGILOGDATAFMT = 65560 SGILOGDATAFMT_FLOAT = 0 SGILOGDATAFMT_16BIT = 1 SGILOGDATAFMT_RAW = 2 SGILOGDATAFMT_8BIT = 3 TIFFTAG_SGILOGENCODE = 65561 SGILOGENCODE_NODITHER = 0 SGILOGENCODE_RANDITHER = 1 EXIFTAG_EXPOSURETIME = 33434 EXIFTAG_FNUMBER = 33437 EXIFTAG_EXPOSUREPROGRAM = 34850 EXIFTAG_SPECTRALSENSITIVITY = 34852 EXIFTAG_ISOSPEEDRATINGS = 34855 EXIFTAG_OECF = 34856 EXIFTAG_EXIFVERSION = 36864 EXIFTAG_DATETIMEORIGINAL = 36867 EXIFTAG_DATETIMEDIGITIZED = 36868 EXIFTAG_COMPONENTSCONFIGURATION = 37121 EXIFTAG_COMPRESSEDBITSPERPIXEL = 37122 EXIFTAG_SHUTTERSPEEDVALUE = 37377 EXIFTAG_APERTUREVALUE = 37378 EXIFTAG_BRIGHTNESSVALUE = 37379 EXIFTAG_EXPOSUREBIASVALUE = 37380 EXIFTAG_MAXAPERTUREVALUE = 37381 EXIFTAG_SUBJECTDISTANCE = 37382 EXIFTAG_METERINGMODE = 37383 EXIFTAG_LIGHTSOURCE = 37384 EXIFTAG_FLASH = 37385 EXIFTAG_FOCALLENGTH = 37386 EXIFTAG_SUBJECTAREA = 37396 EXIFTAG_MAKERNOTE = 37500 EXIFTAG_USERCOMMENT = 37510 EXIFTAG_SUBSECTIME = 37520 EXIFTAG_SUBSECTIMEORIGINAL = 37521 EXIFTAG_SUBSECTIMEDIGITIZED = 37522 EXIFTAG_FLASHPIXVERSION = 40960 EXIFTAG_COLORSPACE = 40961 EXIFTAG_PIXELXDIMENSION = 40962 EXIFTAG_PIXELYDIMENSION = 40963 EXIFTAG_RELATEDSOUNDFILE = 40964 EXIFTAG_FLASHENERGY = 41483 EXIFTAG_SPATIALFREQUENCYRESPONSE = 41484 EXIFTAG_FOCALPLANEXRESOLUTION = 41486 EXIFTAG_FOCALPLANEYRESOLUTION = 41487 EXIFTAG_FOCALPLANERESOLUTIONUNIT = 41488 EXIFTAG_SUBJECTLOCATION = 41492 EXIFTAG_EXPOSUREINDEX = 41493 EXIFTAG_SENSINGMETHOD = 41495 EXIFTAG_FILESOURCE = 41728 EXIFTAG_SCENETYPE = 41729 EXIFTAG_CFAPATTERN = 41730 EXIFTAG_CUSTOMRENDERED = 41985 EXIFTAG_EXPOSUREMODE = 41986 EXIFTAG_WHITEBALANCE = 41987 EXIFTAG_DIGITALZOOMRATIO = 41988 EXIFTAG_FOCALLENGTHIN35MMFILM = 41989 EXIFTAG_SCENECAPTURETYPE = 41990 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_CONTRAST = 41992 EXIFTAG_SATURATION = 41993 EXIFTAG_SHARPNESS = 41994 EXIFTAG_DEVICESETTINGDESCRIPTION = 41995 EXIFTAG_SUBJECTDISTANCERANGE = 41996 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_IMAGEUNIQUEID = 42016 pylibtiff-0.3.0~svn78/libtiff/utils.py0000664000175100017510000001337211440524600016751 0ustar tilletille # Author: Pearu Peterson # Created: June 2010 from __future__ import division __all__ = ['bytes2str'] import optparse VERBOSE = False def bytes2str(bytes): l = [] Pbytes = bytes//1024**5 if Pbytes: l.append('%sPi' % (Pbytes)) bytes = bytes - 1024**5 * Pbytes Tbytes = bytes//1024**4 if Tbytes: l.append('%sTi' % (Tbytes)) bytes = bytes - 1024**4 * Tbytes Gbytes = bytes//1024**3 if Gbytes: l.append('%sGi' % (Gbytes)) bytes = bytes - 1024**3 * Gbytes Mbytes = bytes//1024**2 if Mbytes: l.append('%sMi' % (Mbytes)) bytes = bytes - 1024**2 * Mbytes kbytes = bytes//1024 if kbytes: l.append('%sKi' % (kbytes)) bytes = bytes - 1024*kbytes if bytes: l.append('%s' % (bytes)) if not l: return '0 bytes' return '+'.join(l) + ' bytes' class Options(optparse.Values): """Holds option keys and values. Examples -------- >>> from iocbio.utils import Options >>> options = Options(a='abc', n=4) >>> print options {'a': 'abc', 'n': 4} >>> options.get(n=5) 4 >>> options.get(m=5) 5 >>> print options {'a': 'abc', 'm': 5, 'n': 4} >>> options2 = Options(options) >>> options.get(k = 6) >>> print options2 # note that updating options will update also options2 {'a': 'abc', 'm': 5, 'n': 4, 'k': 6} See also -------- __init__ """ def __init__(self, *args, **kws): """Construct Options instance. The following constructions are supported: + construct Options instance from keyword arguments:: Options(key1 = value1, key2 = value2, ...) + construct Options instance from :pythonlib:`optparse`.Values instance and override with keyword arguments:: Options(, key1 = value1, ...) + construct Options instance from Options instance:: Options(, key1 = value1, ...) Note that both Options instances will share options data. See also -------- Options """ if len(args)==0: optparse.Values.__init__(self, kws) elif len (args)==1: arg = args[0] if isinstance(arg, Options): self.__dict__ = arg.__dict__ self.__dict__.update(**kws) elif isinstance(arg, optparse.Values): optparse.Values.__init__(self, arg.__dict__) self.__dict__.update(**kws) elif isinstance(arg, type (None)): optparse.Values.__init__(self, kws) else: raise NotImplementedError(`arg`) else: raise NotImplementedError(`args`) def get(self, **kws): """Return option value. For example, ``options.get(key = default_value)`` will return the value of an option with ``key``. If such an option does not exist then update ``options`` and return ``default_value``. Parameters ---------- key = default_value Specify option key and its default value. Returns ------- value Value of the option. See also -------- Options """ assert len (kws)==1,`kws` key, default = kws.items()[0] if key not in self.__dict__: if VERBOSE: print 'Options.get: adding new option: %s=%r' % (key, default) self.__dict__[key] = default value = self.__dict__[key] if value is None: value = self.__dict__[key] = default return value def splitcommandline(line): items, stopchar = splitquote (line) result = [] for item in items: if item[0]==item[-1] and item[0] in '\'"': result.append (item[1:-1]) else: result.extend (item.split()) return result def splitquote(line, stopchar=None, lower=False, quotechars = '"\''): """ Fast LineSplitter. Copied from The F2Py Project. """ items = [] i = 0 while 1: try: char = line[i]; i += 1 except IndexError: break l = [] l_append = l.append nofslashes = 0 if stopchar is None: # search for string start while 1: if char in quotechars and not nofslashes % 2: stopchar = char i -= 1 break if char=='\\': nofslashes += 1 else: nofslashes = 0 l_append(char) try: char = line[i]; i += 1 except IndexError: break if not l: continue item = ''.join(l) if lower: item = item.lower() items.append(item) continue if char==stopchar: # string starts with quotechar l_append(char) try: char = line[i]; i += 1 except IndexError: if l: item = str(''.join(l)) items.append(item) break # else continued string while 1: if char==stopchar and not nofslashes % 2: l_append(char) stopchar = None break if char=='\\': nofslashes += 1 else: nofslashes = 0 l_append(char) try: char = line[i]; i += 1 except IndexError: break if l: item = str(''.join(l)) items.append(item) return items, stopchar pylibtiff-0.3.0~svn78/libtiff/libtiff_ctypes.py0000664000175100017510000010505311656035776020641 0ustar tilletille#!/usr/bin/env python """ Ctypes based wrapper to libtiff library. See TIFF.__doc__ for usage information. Homepage: http://pylibtiff.googlecode.com/ """ __author__ = 'Pearu Peterson' __date__ = 'April 2009' __license__ = 'BSD' __version__ = '0.3-svn' __all__ = ['libtiff', 'TIFF'] import os import sys import numpy as np from numpy import ctypeslib import ctypes import ctypes.util if os.name=='nt': # assume that the directory of libtiff3.dll is in PATH. lib = ctypes.util.find_library('libtiff3') if lib is None: # try default installation path: lib = r'C:\Program Files\GnuWin32\bin\libtiff3.dll' if os.path.isfile (lib): print 'You should add %r to PATH environment variable and reboot.' % (os.path.dirname (lib)) else: lib = None else: if hasattr(sys, 'frozen') and sys.platform == 'darwin' and os.path.exists('../Frameworks/libtiff.dylib'): # py2app support, see Issue 8. lib = '../Frameworks/libtiff.dylib' else: lib = ctypes.util.find_library('tiff') if lib is None: raise ImportError('Failed to find TIFF library. Make sure that libtiff is installed and its location is listed in PATH|LD_LIBRARY_PATH|..') libtiff = ctypes.cdll.LoadLibrary(lib) libtiff.TIFFGetVersion.restype = ctypes.c_char_p libtiff.TIFFGetVersion.argtypes = [] libtiff_version_str = libtiff.TIFFGetVersion() i = libtiff_version_str.lower().split().index('version') assert i!=-1,`libtiff_version_str` libtiff_version = libtiff_version_str.split()[i+1] tiff_h_name = 'tiff_h_%s' % (libtiff_version.replace ('.','_')) try: exec 'import %s as tiff_h' % (tiff_h_name) except ImportError: tiff_h = None if tiff_h is None: include_tiff_h = os.path.join(os.path.split(lib)[0], '..', 'include', 'tiff.h') if not os.path.isfile(include_tiff_h): # fix me for windows: include_tiff_h = os.path.join('/usr','include','tiff.h') if not os.path.isfile(include_tiff_h): raise ValueError('Failed to find TIFF header file (may be need to run: sudo apt-get install libtiff4-dev)') # Read TIFFTAG_* constants for the header file: f = open (include_tiff_h, 'r') l = [] d = {} for line in f.readlines(): if not line.startswith('#define'): continue words = line[7:].lstrip().split()[:2] if len (words)!=2: continue name, value = words i = value.find('/*') if i!=-1: value = value[:i] if value in d: value = d[value] else: value = eval(value) d[name] = value l.append('%s = %s' % (name, value)) f.close() fn = os.path.join (os.path.dirname (os.path.abspath (__file__)), tiff_h_name+'.py') print 'Generating %r' % (fn) f = open(fn, 'w') f.write ('\n'.join(l) + '\n') f.close() else: d = tiff_h.__dict__ d['TIFFTAG_CZ_LSMINFO'] = 34412 define_to_name_map = dict(Orientation={}, Compression={}, PhotoMetric={}, PlanarConfig={}, SampleFormat={}, FillOrder={}, FaxMode={}, TiffTag = {} ) name_to_define_map = dict(Orientation={}, Compression={}, PhotoMetric={}, PlanarConfig={}, SampleFormat={}, FillOrder={}, FaxMode={}, TiffTag = {} ) for name, value in d.items(): if name.startswith ('_'): continue exec '%s = %s' % (name, value) for n in define_to_name_map: if name.startswith(n.upper()): define_to_name_map[n][value] = name name_to_define_map[n][name] = value # types defined by tiff.h class c_ttag_t(ctypes.c_uint): pass class c_tdir_t(ctypes.c_uint16): pass class c_tsample_t(ctypes.c_uint16): pass class c_tstrip_t(ctypes.c_uint32): pass class c_ttile_t(ctypes.c_uint32): pass class c_tsize_t(ctypes.c_int32): pass class c_toff_t(ctypes.c_int32): pass class c_tdata_t(ctypes.c_void_p): pass class c_thandle_t(ctypes.c_void_p): pass tifftags = { #TODO: #TIFFTAG_COLORMAP 3 uint16** 1< or a string containing . """ if tag in ['PixelSizeX', 'PixelSizeY', 'RelativeTime']: descr = self.GetField('ImageDescription') if not descr: return i = descr.find (tag) if i==-1: return value = eval(descr[i+len (tag):].lstrip().split()[0]) return value if isinstance(tag, str): tag = eval('TIFFTAG_' + tag.upper()) t = tifftags.get(tag) if t is None: if not ignore_undefined_tag: print 'Warning: no tag %r defined' % (tag) return data_type, convert = t data = data_type() r = libtiff.TIFFGetField(self, tag, ctypes.byref(data)) if not r: # tag not defined for current directory if not ignore_undefined_tag: print 'Warning: tag %r not defined in currect directory' % (tag) return None return convert(data) #@debug def SetField (self, tag, value): """ Set TIFF field value with tag. tag can be numeric constant TIFFTAG_ or a string containing . """ if isinstance(tag, str): tag = eval('TIFFTAG_' + tag.upper()) t = tifftags.get(tag) if t is None: print 'Warning: no tag %r defined' % (tag) return data_type, convert = t if data_type == ctypes.c_float: data_type = ctypes.c_double data = data_type(value) libtiff.TIFFSetField.argtypes = libtiff.TIFFSetField.argtypes[:-1] + [data_type] r = libtiff.TIFFSetField(self, tag, data) return r def info(self): """ Return a string containing map. """ l = [] l.append ('FileName: %s' % (self.FileName())) for tagname in ['Artist', 'CopyRight', 'DateTime', 'DocumentName', 'HostComputer', 'ImageDescription', 'InkNames', 'Make', 'Model', 'PageName', 'Software', 'TargetPrinter', 'BadFaxLines', 'ConsecutiveBadFaxLines', 'Group3Options', 'Group4Options', 'ImageDepth', 'ImageWidth', 'ImageLength', 'RowsPerStrip', 'SubFileType', 'TileDepth', 'TileLength', 'TileWidth', 'StripByteCounts', 'StripOffSets', 'TileByteCounts', 'TileOffSets', 'BitsPerSample', 'CleanFaxData', 'Compression', 'DataType', 'FillOrder', 'InkSet', 'Matteing', 'MaxSampleValue', 'MinSampleValue', 'Orientation', 'PhotoMetric', 'PlanarConfig', 'Predictor', 'ResolutionUnit', 'SampleFormat', 'YCBCRPositioning', 'JPEGQuality', 'JPEGColorMode', 'JPEGTablesMode', 'FaxMode', 'SMaxSampleValue', 'SMinSampleValue', #'Stonits', 'XPosition', 'YPosition', 'XResolution', 'YResolution', 'PrimaryChromaticities', 'ReferenceBlackWhite', 'WhitePoint', 'YCBCRCoefficients', 'PixelSizeX','PixelSizeY', 'RelativeTime', 'CZ_LSMInfo' ]: v = self.GetField(tagname) if v: if isinstance (v, int): v = define_to_name_map.get(tagname, {}).get(v, v) l.append('%s: %s' % (tagname, v)) if tagname=='CZ_LSMInfo': print CZ_LSMInfo(self) return '\n'.join(l) def copy(self, filename, **kws): """ Copy opened TIFF file to a new file. Use keyword arguments to redefine tag values. Parameters ---------- filename : str Specify the name of file where TIFF file is copied to. compression : {'none', 'lzw', 'deflate', ...} Specify compression scheme. bitspersample : {8,16,32,64,128,256} Specify bit size of a sample. sampleformat : {'uint', 'int', 'float', 'complex'} Specify sample format. """ other = TIFF.open(filename, mode='w') define_rewrite = {} for name, value in kws.items(): define = TIFF.get_tag_define(name) assert define is not None if name=='compression': value = TIFF._fix_compression(value) if name=='sampleformat': value = TIFF._fix_sampleformat(value) define_rewrite[define] = value name_define_list = name_to_define_map['TiffTag'].items() self.SetDirectory(0) self.ReadDirectory() while 1: other.SetDirectory(self.CurrentDirectory()) bits = self.GetField('BitsPerSample') sample_format = self.GetField('SampleFormat') assert bits >=8, `bits, sample_format, dtype` itemsize = bits // 8 dtype = self.get_numpy_type(bits, sample_format) for name, define in name_define_list: orig_value = self.GetField(define) if orig_value is None and define not in define_rewrite: continue if name.endswith('OFFSETS') or name.endswith('BYTECOUNTS'): continue if define in define_rewrite: value = define_rewrite[define] else: value = orig_value if value is None: continue other.SetField(define, value) new_bits = other.GetField('BitsPerSample') new_sample_format = other.GetField('SampleFormat') new_dtype = other.get_numpy_type(new_bits, new_sample_format) assert new_bits >=8, `new_bits, new_sample_format, new_dtype` new_itemsize = new_bits // 8 strip_size = self.StripSize() new_strip_size = self.StripSize() buf = np.zeros(strip_size // itemsize, dtype) for strip in range(self.NumberOfStrips()): elem = self.ReadEncodedStrip(strip, buf.ctypes.data, strip_size) if elem>0: new_buf = buf.astype(new_dtype) other.WriteEncodedStrip(strip, new_buf.ctypes.data, (elem * new_itemsize)//itemsize) self.ReadDirectory() if self.LastDirectory (): break other.close () import struct import numpy class CZ_LSMInfo: def __init__(self, tiff): self.tiff = tiff self.filename = tiff.FileName() self.offset = tiff.GetField(TIFFTAG_CZ_LSMINFO) self.extract_info() def extract_info (self): if self.offset is None: return f = libtiff.TIFFFileno(self.tiff) fd = os.fdopen(f, 'r') pos = fd.tell() self.offset = self.tiff.GetField(TIFFTAG_CZ_LSMINFO) print os.lseek(f, 0, 1) print pos #print libtiff.TIFFSeekProc(self.tiff, 0, 1) fd.seek(0) print struct.unpack ('HH', fd.read (4)) print struct.unpack('I',fd.read (4)) print struct.unpack('H',fd.read (2)) fd.seek(self.offset) d = [('magic_number', 'i4'), ('structure_size', 'i4')] print pos, numpy.rec.fromfile(fd, d, 1) fd.seek(pos) #print hex (struct.unpack('I', fd.read (4))[0]) #fd.close() def __str__ (self): return '%s: %s' % (self.filename, self.offset) libtiff.TIFFOpen.restype = TIFF libtiff.TIFFOpen.argtypes = [ctypes.c_char_p, ctypes.c_char_p] libtiff.TIFFFileName.restype = ctypes.c_char_p libtiff.TIFFFileName.argtypes = [TIFF] libtiff.TIFFFileno.restype = ctypes.c_int libtiff.TIFFFileno.argtypes = [TIFF] libtiff.TIFFCurrentRow.restype = ctypes.c_uint32 libtiff.TIFFCurrentRow.argtypes = [TIFF] libtiff.TIFFCurrentStrip.restype = c_tstrip_t libtiff.TIFFCurrentStrip.argtypes = [TIFF] libtiff.TIFFCurrentTile.restype = c_ttile_t libtiff.TIFFCurrentTile.argtypes = [TIFF] libtiff.TIFFCurrentDirectory.restype = c_tdir_t libtiff.TIFFCurrentDirectory.argtypes = [TIFF] libtiff.TIFFLastDirectory.restype = ctypes.c_int libtiff.TIFFLastDirectory.argtypes = [TIFF] libtiff.TIFFReadDirectory.restype = ctypes.c_int libtiff.TIFFReadDirectory.argtypes = [TIFF] libtiff.TIFFWriteDirectory.restype = ctypes.c_int libtiff.TIFFWriteDirectory.argtypes = [TIFF] libtiff.TIFFSetDirectory.restype = ctypes.c_int libtiff.TIFFSetDirectory.argtypes = [TIFF, c_tdir_t] libtiff.TIFFFileno.restype = ctypes.c_int libtiff.TIFFFileno.argtypes = [TIFF] libtiff.TIFFGetMode.restype = ctypes.c_int libtiff.TIFFGetMode.argtypes = [TIFF] libtiff.TIFFIsTiled.restype = ctypes.c_int libtiff.TIFFIsTiled.argtypes = [TIFF] libtiff.TIFFIsByteSwapped.restype = ctypes.c_int libtiff.TIFFIsByteSwapped.argtypes = [TIFF] libtiff.TIFFIsUpSampled.restype = ctypes.c_int libtiff.TIFFIsUpSampled.argtypes = [TIFF] libtiff.TIFFIsMSB2LSB.restype = ctypes.c_int libtiff.TIFFIsMSB2LSB.argtypes = [TIFF] libtiff.TIFFGetField.restype = ctypes.c_int libtiff.TIFFGetField.argtypes = [TIFF, c_ttag_t, ctypes.c_void_p] libtiff.TIFFSetField.restype = ctypes.c_int libtiff.TIFFSetField.argtypes = [TIFF, c_ttag_t, ctypes.c_void_p] # last item is reset in TIFF.SetField method libtiff.TIFFNumberOfStrips.restype = c_tstrip_t libtiff.TIFFNumberOfStrips.argtypes = [TIFF] libtiff.TIFFReadRawStrip.restype = c_tsize_t libtiff.TIFFReadRawStrip.argtypes = [TIFF, c_tstrip_t, c_tdata_t, c_tsize_t] libtiff.TIFFWriteRawStrip.restype = c_tsize_t libtiff.TIFFWriteRawStrip.argtypes = [TIFF, c_tstrip_t, c_tdata_t, c_tsize_t] libtiff.TIFFReadEncodedStrip.restype = c_tsize_t libtiff.TIFFReadEncodedStrip.argtypes = [TIFF, c_tstrip_t, c_tdata_t, c_tsize_t] libtiff.TIFFWriteEncodedStrip.restype = c_tsize_t libtiff.TIFFWriteEncodedStrip.argtypes = [TIFF, c_tstrip_t, c_tdata_t, c_tsize_t] libtiff.TIFFStripSize.restype = c_tsize_t libtiff.TIFFStripSize.argtypes = [TIFF] libtiff.TIFFRawStripSize.restype = c_tsize_t libtiff.TIFFRawStripSize.argtypes = [TIFF, c_tstrip_t] libtiff.TIFFClose.restype = None libtiff.TIFFClose.argtypes = [TIFF] # Support for TIFF warning and error handlers: TIFFWarningHandler = ctypes.CFUNCTYPE(None, ctypes.c_char_p, # Module ctypes.c_char_p, # Format ctypes.c_void_p) # va_list TIFFErrorHandler = ctypes.CFUNCTYPE(None, ctypes.c_char_p, # Module ctypes.c_char_p, # Format ctypes.c_void_p) # va_list # This has to be at module scope so it is not garbage-collected _null_warning_handler = TIFFWarningHandler(lambda module, fmt, va_list: None) _null_error_handler = TIFFErrorHandler(lambda module, fmt, va_list: None) def suppress_warnings(): libtiff.TIFFSetWarningHandler(_null_warning_handler) def suppress_errors(): libtiff.TIFFSetErrorHandler(_null_error_handler) def _test_read(filename=None): import sys import time if filename is None: if len(sys.argv) != 2: print 'Run `libtiff.py ` for testing.' return filename = sys.argv[1] print 'Trying to open', filename, '...', tiff = TIFF.open(filename) print 'ok' print 'Trying to show info ...\n','-'*10 print tiff.info() print '-'*10,'ok' print 'Trying show images ...' t = time.time () i = 0 for image in tiff.iter_images(verbose=True): #print image.min(), image.max(), image.mean () i += 1 print '\tok',(time.time ()-t)*1e3,'ms',i,'images' def _test_write(): tiff = TIFF.open('/tmp/libtiff_test_write.tiff', mode='w') arr = np.zeros ((5,6), np.uint32) for i in range(arr.shape[0]): for j in range (arr.shape[1]): arr[i,j] = i + 10*j print arr tiff.write_image(arr) del tiff def _test_write_float(): tiff = TIFF.open('/tmp/libtiff_test_write.tiff', mode='w') arr = np.zeros ((5,6), np.float64) for i in range(arr.shape[0]): for j in range (arr.shape[1]): arr[i,j] = i + 10*j print arr tiff.write_image(arr) del tiff tiff = TIFF.open('/tmp/libtiff_test_write.tiff', mode='r') print tiff.info() arr2 = tiff.read_image() print arr2 def _test_copy(): tiff = TIFF.open('/tmp/libtiff_test_compression.tiff', mode='w') arr = np.zeros ((5,6), np.uint32) for i in range(arr.shape[0]): for j in range (arr.shape[1]): arr[i,j] = 1+i + 10*j #from scipy.stats import poisson #arr = poisson.rvs (arr) tiff.SetField('ImageDescription', 'Hey\nyou') tiff.write_image(arr, compression='lzw') del tiff tiff = TIFF.open('/tmp/libtiff_test_compression.tiff', mode='r') print tiff.info() arr2 = tiff.read_image() assert (arr==arr2).all(),'arrays not equal' for compression in ['none','lzw','deflate']: for sampleformat in ['int','uint','float']: for bitspersample in [256,128,64,32,16,8]: if sampleformat=='float' and (bitspersample < 32 or bitspersample > 128): continue if sampleformat in ['int','uint'] and bitspersample > 64: continue #print compression, sampleformat, bitspersample tiff.copy ('/tmp/libtiff_test_copy2.tiff', compression=compression, imagedescription='hoo', sampleformat=sampleformat, bitspersample=bitspersample) tiff2 = TIFF.open('/tmp/libtiff_test_copy2.tiff', mode='r') arr3 = tiff2.read_image() assert (arr==arr3).all(),'arrays not equal %r' % ((compression, sampleformat, bitspersample),) print 'test copy ok' if __name__=='__main__': #_test_write_float() #_test_write() _test_read() #_test_copy() pylibtiff-0.3.0~svn78/libtiff/tiff_file.py0000664000175100017510000011335111625020022017530 0ustar tilletille""" Provides TIFFfile class. """ # Author: Pearu Peterson # Created: June 2010 from __future__ import division __all__ = ['TIFFfile', 'TiffFile'] import os import sys import numpy from numpy.testing.utils import memusage from .tiff_data import type2name, name2type, type2bytes, type2dtype, tag_value2name, tag_name2value from .tiff_data import LittleEndianNumpyDTypes, BigEndianNumpyDTypes, default_tag_values, sample_format_map from .utils import bytes2str from .tiff_base import TiffBase from .tiff_sample_plane import TiffSamplePlane from .tiff_array import TiffArray import lsm import tif_lzw IFDEntry_init_hooks = [] IFDEntry_finalize_hooks = [] class TIFFfile(TiffBase): """ Hold a TIFF file image stack that is accessed via memmap. To access image, use get_tiff_array method. Attributes ---------- filename : str data : memmap IFD : IFD-list See also -------- TiffFiles, TiffChannelsAndFiles """ def close(self): if hasattr(self, 'data'): if self.verbose: sys.stdout.write('Closing TIFF file %r\n' % (self.filename)); sys.stdout.flush() del self.data __del__ = close def __init__(self, filename, mode='r', first_byte = 0, verbose=False): if verbose: sys.stdout.write ('Opening file %r\n' % (filename)); sys.stdout.flush() self.verbose = verbose self.filename = filename if mode!='r': raise NotImplementedError(`mode`) if not os.path.isfile (filename): raise ValueError ('file does not exists') if not os.stat(filename).st_size: raise ValueError ('file has zero size') self.first_byte = first_byte try: self.data = numpy.memmap(filename, dtype=numpy.ubyte, mode=mode) except IOError, msg: if 'Too many open files' in str (msg): print '''\ ====================================================================== An exception was raised with message: %s Ubuntu Linux users: Check `ulimit -n`. To increase the number of open files limits, add the following lines * hard nofile 16384 * soft nofile 16384 to /etc/security/limits.conf and run `sudo start procps` ====================================================================== ''' % (msg) raise IOError ('%s' % (msg)) if 'Operation not permitted' in str (msg): print '''\ ====================================================================== An exception was raised with message: %s The exception may be due to unsufficient access rights or due to opening too many files for the given file system. ====================================================================== ''' % (msg) raise IOError ('%s' % (msg)) raise self.memory_usage = [(self.data.nbytes, self.data.nbytes, 'eof')] byteorder = self.data[first_byte:first_byte+2].view(dtype=numpy.uint16)[0] if byteorder==0x4949: self.endian = 'little' self.dtypes = LittleEndianNumpyDTypes elif byteorder==0x4d4d: self.endian = 'big' self.dtypes = BigEndianNumpyDTypes else: raise ValueError('unrecognized byteorder: %s' % (hex(byteorder))) magic = self.get_uint16(first_byte+2) if magic!=42: raise ValueError('wrong magic number for TIFF file: %s' % (magic)) self.IFD0 = IFD0 = first_byte + self.get_uint32(first_byte+4) self.memory_usage.append((first_byte, first_byte+8, 'file header')) n = self.get_uint16(IFD0) IFD_list = [] IFD_offset = IFD0 while IFD_offset: n = self.get_uint16(IFD_offset) ifd = IFD(self) for i in range(n): entry = IFDEntry(ifd, self, IFD_offset + 2 + i*12) ifd.append(entry) ifd.finalize() IFD_list.append(ifd) self.memory_usage.append((IFD_offset, IFD_offset + 2 + n*12 + 4, 'IFD%s entries (%s)' % (len(IFD_list), len(ifd)))) IFD_offset = self.get_uint32(IFD_offset + 2 + n*12) if verbose: sys.stdout.write('\rIFD information read: %s..' % (len (IFD_list))); sys.stdout.flush() self.IFD = IFD_list if verbose: sys.stdout.write(' done\n'); sys.stdout.flush() self.time = None def set_time (self, time): self.time = time def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.filename) def get_uint16(self, offset): return self.data[offset:offset+2].view(dtype=self.dtypes.uint16)[0] def get_uint32(self, offset): return self.data[offset:offset+4].view(dtype=self.dtypes.uint32)[0] def get_int16(self, offset): return self.data[offset:offset+2].view(dtype=self.dtypes.int16)[0] def get_int32(self, offset): return self.data[offset:offset+4].view(dtype=self.dtypes.int32)[0] def get_float32(self, offset): return self.data[offset:offset+4].view(dtype=self.dtypes.float32)[0] def get_float64(self, offset): return self.data[offset:offset+8].view(dtype=self.dtypes.float64)[0] get_short = get_uint16 get_long = get_uint32 get_double = get_float64 def get_value(self, offset, typ): values = self.get_values(offset, typ, 1) if values is not None: return values[0] def get_values(self, offset, typ, count): if isinstance(typ, numpy.dtype): dtype = typ bytes = typ.itemsize elif isinstance(typ, type) and issubclass(typ, numpy.generic): dtype = typ bytes = typ().itemsize else: if isinstance(typ, str): ntyp = typ typ = name2type.get(typ) else: ntyp = str (typ) dtype = self.dtypes.type2dt.get(typ) bytes = type2bytes.get(typ) if dtype is None or bytes is None: sys.stderr.write('get_values: incomplete info for type=%r [%r]: dtype=%s, bytes=%s\n' % (typ,ntyp, dtype, bytes)) return return self.data[offset:offset+bytes*count].view(dtype=dtype) def get_string(self, offset, length = None): if length is None: i = 0 while self.data[offset+i]: i += 1 length = i string = self.get_values(offset, 'BYTE', length).tostring() return string def check_memory_usage(self, verbose=True): ''' Check memory usage of TIFF fields and blocks. Returns ------- ok : bool Return False if unknown or overlapping memory areas have been detected. ''' l = [] l.extend(self.memory_usage) for ifd in self.IFD: l.extend(ifd.memory_usage) l.sort() last_end = None ok = True for start, end, resource in l: if last_end: if last_end!=start: if verbose: print '--- unknown %s bytes' % (start-last_end) ok = False if start0: if i==1: step = l[-1][0] - l[-2][1] assert step>=0,`step, l[-2], l[-1]` else: if step != l[-1][0] - l[-2][1]: can_return_memmap = False #assert step == l[-1][0] - l[-2][1],`step, l[-2], l[-1], (l[-1][0] - l[-2][1]), i` i += 1 if verbose: bytes_per_image_str = bytes2str(bytes_per_image) print ''' width : %(width)s length : %(length)s depth : %(depth)s sample_format : %(format)s samples_per_pixel : %(samples_per_pixel)s planar_config : %(planar_config)s bits_per_sample : %(bits_per_sample)s bits_per_pixel : %(bits_per_pixel)s bytes_per_pixel : %(bytes_per_pixel)s bytes_per_row : %(bytes_per_row)s bytes_per_image : %(bytes_per_image_str)s strips_per_image : %(strips_per_image)s rows_per_strip : %(rows_per_strip)s strip_length : %(strip_length_str)s ''' % (locals ()) if photometric_interpretation==2: assert samples_per_pixel==3, `samples_per_pixel` sample_names = ['red', 'green', 'blue'] else: sample_names = ['sample%s' % (j) for j in range (samples_per_pixel)] depth = i if not can_return_memmap: if planar_config==1: if samples_per_pixel==1: i = 0 arr = numpy.empty(depth * bytes_per_image, dtype=self.dtypes.uint8) bytes_per_strip = rows_per_strip * bytes_per_row for start, end in full_l: #sys.stdout.write ("%s:%s," % (start, end)); sys.stdout.flush () if compression==1: # none d = self.data[start:end] elif compression==5: # lzw d = self.data[start:end] d = tif_lzw.decode(d, bytes_per_strip) arr[i:i+d.nbytes] = d i += d.nbytes arr = arr.view(dtype=dtype_lst[0]).reshape((depth, length, width)) return [arr], sample_names else: i = 0 arr = numpy.empty(depth * bytes_per_image, dtype=self.dtypes.uint8) bytes_per_strip = rows_per_strip * bytes_per_row for start, end in full_l: sys.stdout.write ("%s:%s," % (start, end)); sys.stdout.flush () if compression==1: # none d = self.data[start:end] elif compression==5: # lzw d = self.data[start:end] d = tif_lzw.decode(d, bytes_per_strip) arr[i:i+d.nbytes] = d i += d.nbytes dt = numpy.dtype(dict(names=sample_names, formats=dtype_lst)) arr = arr.view(dtype=dt).reshape((depth, length, width)) return [arr[n] for n in arr.dtype.names], arr.dtype.names raise NotImplementedError(`depth, bytes_per_image, samples_per_pixel`) else: raise NotImplementedError (`planar_config`) start = l[0][0] end = l[-1][1] if start > step: arr = self.data[start - step: end].reshape((depth, strip_length + step)) k = step elif end <= self.data.size - step: arr = self.data[start: end+step].reshape((depth, strip_length + step)) k = 0 else: raise NotImplementedError (`start, end, step`) sys.stdout.flush() if planar_config==2: if self.is_lsm: # LSM510: one strip per image plane channel if subfile_type==0: sample_names = self.lsminfo.get('data channel name') elif subfile_type==1: sample_names = ['red', 'green', 'blue'] assert samples_per_pixel==3,`samples_per_pixel` else: raise NotImplementedError (`subfile_type`) samples = [] for j in range(samples_per_pixel): bytes = bits_per_sample[j] // 8 * width * length tmp = arr[:,k:k+bytes] tmp = tmp.view(dtype=dtype_lst[j]) tmp = tmp.reshape((depth, length, width)) samples.append(tmp) k += bytes return samples, sample_names raise NotImplementedError (`planar_config, self.is_lsm`) elif planar_config==1: samples = [] bytes = sum(bits_per_sample[:samples_per_pixel]) // 8 * width * length bytes_per_sample = bits_per_sample // 8 for j in range(samples_per_pixel): i0 = k+j*bytes_per_sample[j] #print j, i0, i0+bytes, samples_per_pixel, arr.shape tmp = arr[:,i0:i0+bytes:samples_per_pixel] tmp = numpy.array(tmp.reshape((tmp.size,))) tmp = tmp.view(dtype=dtype_lst[j]) tmp = tmp.reshape((depth, length, width)) samples.append(tmp) #k += bytes return samples, sample_names else: raise NotImplementedError (`planar_config`) def get_info (self): """ Return basic information about the file. """ l = [] subfile_types = self.get_subfile_types() l.append ('Number of subfile types: %s' % (len (subfile_types))) for subfile_type in subfile_types: ifd = self.get_first_ifd(subfile_type=subfile_type) l.append ('-'*50) l.append('Subfile type: %s' % (subfile_type)) l.append('Number of images: %s' % (self.get_depth(subfile_type = subfile_type))) for tag in ['ImageLength', 'ImageWidth', 'SamplesPerPixel','ExtraSamples', 'SampleFormat', 'Compression','Predictor', 'PhotometricInterpretation', 'Orientation', 'PlanarConfiguration', 'MinSampleValue', 'MaxSampleValue', 'XResolution', 'YResolution','ResolutionUnit', 'XPosition','YPosition', 'DocumentName', 'Software', 'HostComputer', 'Artist', 'DateTime', 'Make','Model','Copyright', 'ImageDescription', ]: v = ifd.get_value(tag, human=True) if v is None: continue if tag=='ImageDescription' and subfile_type==0: if v.startswith (' #define NPY_NO_DEPRECATED_API #define PY_ARRAY_UNIQUE_SYMBOL PyArray_API #include "numpy/arrayobject.h" #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif #define CHAR_BITS 8 #define CHAR_BITS_EXP 3 /* i/8 == i>>3 */ #define BITS(bytes) (((unsigned long)(bytes)) << CHAR_BITS_EXP) #define BYTES(bits) (((bits) == 0) ? 0 : ((((bits) - 1) >> CHAR_BITS_EXP) + 1)) #define NBYTES(bits) ((bits) >> CHAR_BITS_EXP) #define BITMASK(i,width) (((unsigned long) 1) << (((i))%(width))) #define DATAPTR(data, i) ((char*)(data) + ((i)>>CHAR_BITS_EXP)) #define DATA(data, i) (*DATAPTR((data),(i))) #define GETBIT(value, i, width) ((value & BITMASK((i),(width))) ? 1 : 0) #define ARRGETBIT(arr, i) ((DATA(PyArray_DATA((PyArrayObject*)arr), (i)) & BITMASK((i),CHAR_BITS)) ? 1 : 0) static PyObject *getbit(PyObject *self, PyObject *args, PyObject *kwds) { PyObject* arr = NULL; char bit = 0; Py_ssize_t index = 0; static char* kwlist[] = {"array", "index", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:getbit", kwlist, &arr, &index)) return NULL; if (!PyArray_Check(arr)) { PyErr_SetString(PyExc_TypeError,"first argument must be array object"); return NULL; } if (index >= BITS(PyArray_NBYTES((PyArrayObject*)arr))) { PyErr_SetString(PyExc_IndexError,"bit index out of range"); return NULL; } bit = ARRGETBIT(arr, index); return Py_BuildValue("b",bit); } static PyObject *setbit(PyObject *self, PyObject *args, PyObject *kwds) { PyObject* arr = NULL; char bit = 0, opt=0; Py_ssize_t index = 0; static char* kwlist[] = {"array", "index", "bit", "opt", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Onbb:setbit", kwlist, &arr, &index, &bit, &opt)) return NULL; if (!opt) { if (!PyArray_Check(arr)) { PyErr_SetString(PyExc_TypeError,"first argument must be array object"); return NULL; } if (NBYTES(index) >= PyArray_NBYTES((PyArrayObject*)arr)) { PyErr_SetString(PyExc_IndexError,"bit index out of range"); return NULL; } } if (bit) DATA(PyArray_DATA((PyArrayObject*)arr), index) |= BITMASK(index, CHAR_BITS); else DATA(PyArray_DATA((PyArrayObject*)arr), index) &= ~BITMASK(index, CHAR_BITS); Py_INCREF(Py_None); return Py_None; } static PyObject *getword(PyObject *self, PyObject *args, PyObject *kwds) { PyObject* arr = NULL; Py_ssize_t index = 0; Py_ssize_t width = 0, i; static char* kwlist[] = {"array", "index", "width", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Onn:getword", kwlist, &arr, &index, &width)) return NULL; if (!PyArray_Check(arr)) { PyErr_SetString(PyExc_TypeError,"first argument must be array object"); return NULL; } if (((index+width-1) >= BITS(PyArray_NBYTES((PyArrayObject*)arr))) || (width<0)) { PyErr_SetString(PyExc_IndexError,"bit index out of range"); return NULL; } // fast code, at least 3x if (width<=32) { npy_uint32 x = *((npy_uint64*)DATAPTR(PyArray_DATA((PyArrayObject*)arr), index)) >> (index % CHAR_BITS); return Py_BuildValue("kn",x & (NPY_MAX_UINT32>>(32-width)), index+width); } // generic code if (width<=64) { npy_uint64 word = 0; for (i=0; i= BITS(PyArray_NBYTES((PyArrayObject*)arr)) || width<0) { printf("index,width,nbits=%d,%d,%d\n", index, width, BITS(PyArray_NBYTES((PyArrayObject*)arr))); PyErr_SetString(PyExc_IndexError,"bit index out of range"); return NULL; } if (width>64) { PyErr_SetString(PyExc_ValueError,"bit width must not be larger than 64"); return NULL; } } for (i=0; i #define NPY_NO_DEPRECATED_API #define PY_ARRAY_UNIQUE_SYMBOL PyArray_API #include "numpy/arrayobject.h" #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif typedef signed int tmsize_t; typedef tmsize_t tsize_t; typedef npy_uint8 uint8; typedef npy_uint16 uint16; typedef struct { uint8* tif_data; /* compression scheme private data */ uint8* tif_rawdata; /* raw data buffer */ tmsize_t tif_rawdatasize; /* # of bytes in raw data buffer */ uint8* tif_rawcp; /* current spot in raw buffer */ tmsize_t tif_rawcc; /* bytes unread from raw buffer */ } TIFF; //#include "tif_predict.h" #include /* * NB: The 5.0 spec describes a different algorithm than Aldus * implements. Specifically, Aldus does code length transitions * one code earlier than should be done (for real LZW). * Earlier versions of this library implemented the correct * LZW algorithm, but emitted codes in a bit order opposite * to the TIFF spec. Thus, to maintain compatibility w/ Aldus * we interpret MSB-LSB ordered codes to be images written w/ * old versions of this library, but otherwise adhere to the * Aldus "off by one" algorithm. * * Future revisions to the TIFF spec are expected to "clarify this issue". */ //#define LZW_COMPAT /* include backwards compatibility code */ /* * Each strip of data is supposed to be terminated by a CODE_EOI. * If the following #define is included, the decoder will also * check for end-of-strip w/o seeing this code. This makes the * library more robust, but also slower. */ #define LZW_CHECKEOS /* include checks for strips w/o EOI code */ #define MAXCODE(n) ((1L<<(n))-1) /* * The TIFF spec specifies that encoded bit * strings range from 9 to 12 bits. */ #define BITS_MIN 9 /* start with 9 bits */ #define BITS_MAX 12 /* max of 12 bit strings */ /* predefined codes */ #define CODE_CLEAR 256 /* code to clear string table */ #define CODE_EOI 257 /* end-of-information code */ #define CODE_FIRST 258 /* first free code entry */ #define CODE_MAX MAXCODE(BITS_MAX) #define HSIZE 9001L /* 91% occupancy */ #define HSHIFT (13-8) #ifdef LZW_COMPAT /* NB: +1024 is for compatibility with old files */ #define CSIZE (MAXCODE(BITS_MAX)+1024L) #else #define CSIZE (MAXCODE(BITS_MAX)+1L) #endif /* * State block for each open TIFF file using LZW * compression/decompression. Note that the predictor * state block must be first in this data structure. */ typedef struct { // TIFFPredictorState predict; /* predictor super class */ unsigned short nbits; /* # of bits/code */ unsigned short maxcode; /* maximum code for lzw_nbits */ unsigned short free_ent; /* next free entry in hash table */ long nextdata; /* next bits of i/o */ long nextbits; /* # of valid bits in lzw_nextdata */ //int rw_mode; /* preserve rw_mode from init */ } LZWBaseState; #define lzw_nbits base.nbits #define lzw_maxcode base.maxcode #define lzw_free_ent base.free_ent #define lzw_nextdata base.nextdata #define lzw_nextbits base.nextbits /* * Encoding-specific state. */ typedef uint16 hcode_t; /* codes fit in 16 bits */ typedef struct { long hash; hcode_t code; } hash_t; /* * Decoding-specific state. */ typedef struct code_ent { struct code_ent *next; unsigned short length; /* string len, including this token */ unsigned char value; /* data value */ unsigned char firstchar; /* first token of string */ } code_t; //typedef int (*decodeFunc)(TIFF*, uint8*, tmsize_t, uint16); typedef struct { LZWBaseState base; /* Decoding specific data */ long dec_nbitsmask; /* lzw_nbits 1 bits, right adjusted */ long dec_restart; /* restart count */ #ifdef LZW_CHECKEOS tmsize_t dec_bitsleft; /* available bits in raw data */ #endif //decodeFunc dec_decode; /* regular or backwards compatible */ code_t* dec_codep; /* current recognized code */ code_t* dec_oldcodep; /* previously recognized code */ code_t* dec_free_entp; /* next free entry */ code_t* dec_maxcodep; /* max available entry */ code_t* dec_codetab; /* kept separate for small machines */ /* Encoding specific data */ int enc_oldcode; /* last code encountered */ long enc_checkpoint; /* point at which to clear table */ #define CHECK_GAP 10000 /* enc_ratio check interval */ long enc_ratio; /* current compression ratio */ long enc_incount; /* (input) data bytes encoded */ long enc_outcount; /* encoded (output) bytes */ uint8* enc_rawlimit; /* bound on tif_rawdata buffer */ hash_t* enc_hashtab; /* kept separate for small machines */ } LZWCodecState; #define LZWState(tif) ((LZWBaseState*) (tif)->tif_data) #define DecoderState(tif) ((LZWCodecState*) LZWState(tif)) #define EncoderState(tif) ((LZWCodecState*) LZWState(tif)) //static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s); #ifdef LZW_COMPAT static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s); #endif static void cl_hash(LZWCodecState*); /* * LZW Decoder. */ #ifdef LZW_CHECKEOS /* * This check shouldn't be necessary because each * strip is suppose to be terminated with CODE_EOI. */ #define NextCode(_tif, _sp, _bp, _code, _get) { \ if ((_sp)->dec_bitsleft < (tmsize_t)nbits) { \ /*TIFFWarningExt(_tif->tif_clientdata, module,*/ \ /* "LZWDecode: Strip %d not terminated with EOI code", */ \ /* _tif->tif_curstrip);*/ \ _code = CODE_EOI; \ } else { \ _get(_sp,_bp,_code); \ (_sp)->dec_bitsleft -= nbits; \ } \ } #else #define NextCode(tif, sp, bp, code, get) get(sp, bp, code) #endif #if 1 static int LZWSetupDecode(TIFF* tif) { LZWCodecState* sp = DecoderState(tif); int code; if( sp == NULL ) { /* * Allocate state block so tag methods have storage to record * values. */ //tif->tif_data = (uint8*) TIFFmalloc(sizeof(LZWCodecState)); tif->tif_data = (uint8*) malloc(sizeof(LZWCodecState)); if (tif->tif_data == NULL) { //TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block"); return (0); } DecoderState(tif)->dec_codetab = NULL; //DecoderState(tif)->dec_decode = NULL; /* * Setup predictor setup. */ //(void) TIFFPredictorInit(tif); sp = DecoderState(tif); } assert(sp != NULL); if (sp->dec_codetab == NULL) { //sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t)); sp->dec_codetab = (code_t*)malloc(CSIZE*sizeof (code_t)); if (sp->dec_codetab == NULL) { //TIFFErrorExt(tif->tif_clientdata, module, // "No space for LZW code table"); return (0); } /* * Pre-load the table. */ code = 255; do { sp->dec_codetab[code].value = code; sp->dec_codetab[code].firstchar = code; sp->dec_codetab[code].length = 1; sp->dec_codetab[code].next = NULL; } while (code--); /* * Zero-out the unused entries */ //_TIFFmemset(&sp->dec_codetab[CODE_CLEAR], 0, // (CODE_FIRST - CODE_CLEAR) * sizeof (code_t)); memset(&sp->dec_codetab[CODE_CLEAR], 0, (CODE_FIRST - CODE_CLEAR) * sizeof (code_t)); } return (1); } /* * Setup state for decoding a strip. */ static int LZWPreDecode(TIFF* tif) { LZWCodecState *sp = DecoderState(tif); //(void) s; assert(sp != NULL); if( sp->dec_codetab == NULL ) { //tif->tif_setupdecode( tif ); LZWSetupDecode(tif); } /* * Check for old bit-reversed codes. */ if (tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) { #ifdef LZW_COMPAT if (!sp->dec_decode) { TIFFWarningExt(tif->tif_clientdata, module, "Old-style LZW codes, convert file"); /* * Override default decoding methods with * ones that deal with the old coding. * Otherwise the predictor versions set * above will call the compatibility routines * through the dec_decode method. */ tif->tif_decoderow = LZWDecodeCompat; tif->tif_decodestrip = LZWDecodeCompat; tif->tif_decodetile = LZWDecodeCompat; /* * If doing horizontal differencing, must * re-setup the predictor logic since we * switched the basic decoder methods... */ (*tif->tif_setupdecode)(tif); sp->dec_decode = LZWDecodeCompat; } sp->lzw_maxcode = MAXCODE(BITS_MIN); #else /* !LZW_COMPAT */ //if (!sp->dec_decode) { //TIFFErrorExt(tif->tif_clientdata, module, // "Old-style LZW codes not supported"); //sp->dec_decode = LZWDecode; //} return (0); #endif/* !LZW_COMPAT */ } else { sp->lzw_maxcode = MAXCODE(BITS_MIN)-1; //sp->dec_decode = LZWDecode; } sp->lzw_nbits = BITS_MIN; sp->lzw_nextbits = 0; sp->lzw_nextdata = 0; sp->dec_restart = 0; sp->dec_nbitsmask = MAXCODE(BITS_MIN); #ifdef LZW_CHECKEOS sp->dec_bitsleft = tif->tif_rawcc << 3; #endif sp->dec_free_entp = sp->dec_codetab + CODE_FIRST; /* * Zero entries that are not yet filled in. We do * this to guard against bogus input data that causes * us to index into undefined entries. If you can * come up with a way to safely bounds-check input codes * while decoding then you can remove this operation. */ //_TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t)); memset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t)); sp->dec_oldcodep = &sp->dec_codetab[-1]; sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1]; return (1); } /* * Decode a "hunk of data". */ #define GetNextCode(sp, bp, code) { \ nextdata = (nextdata<<8) | *(bp)++; \ nextbits += 8; \ if (nextbits < nbits) { \ nextdata = (nextdata<<8) | *(bp)++; \ nextbits += 8; \ } \ code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask); \ nextbits -= nbits; \ } static void codeLoop(TIFF* tif) { //TIFFErrorExt(tif->tif_clientdata, module, // "Bogus encoding, loop in the code table; scanline %d", // tif->tif_row); } static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0) { LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; hcode_t code; int len; long nbits, nextbits, nextdata, nbitsmask; code_t *codep, *free_entp, *maxcodep, *oldcodep; //(void) s; assert(sp != NULL); assert(sp->dec_codetab != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ && codep); if (codep) { tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); } return (1); } /* * Residue satisfies only part of the decode request. */ op += residue, occ -= residue; tp = op; do { int t; --tp; t = codep->value; codep = codep->next; *tp = t; } while (--residue && codep); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCode); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { free_entp = sp->dec_codetab + CODE_FIRST; //_TIFFmemset(free_entp, 0, // (CSIZE - CODE_FIRST) * sizeof (code_t)); memset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask-1; NextCode(tif, sp, bp, code, GetNextCode); if (code == CODE_EOI) break; if (code >= CODE_CLEAR) { //TIFFErrorExt(tif->tif_clientdata, tif->tif_name, //"LZWDecode: Corrupted LZW table at scanline %d", // tif->tif_row); return (0); } *op++ = (char)code, occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { //TIFFErrorExt(tif->tif_clientdata, module, // "Corrupted LZW table at scanline %d", // tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { //TIFFErrorExt(tif->tif_clientdata, module, // "Corrupted LZW table at scanline %d", // tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask-1; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { // TIFFErrorExt(tif->tif_clientdata, module, // "Wrong length of decoded string: " // "data probably corrupted at scanline %d", // tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep && codep->length > occ); if (codep) { sp->dec_restart = (long)occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); if (codep) codeLoop(tif); } break; } len = codep->length; tp = op + len; do { int t; --tp; t = codep->value; codep = codep->next; *tp = t; } while (codep && tp > op); if (codep) { codeLoop(tif); break; } assert(occ >= len); op += len, occ -= len; } else *op++ = (char)code, occ--; } tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short) nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; return (occ); // return extra bytes for resizing result array } #ifdef LZW_COMPAT /* * Decode a "hunk of data" for old images. */ #define GetNextCodeCompat(sp, bp, code) { \ nextdata |= (unsigned long) *(bp)++ << nextbits; \ nextbits += 8; \ if (nextbits < nbits) { \ nextdata |= (unsigned long) *(bp)++ << nextbits;\ nextbits += 8; \ } \ code = (hcode_t)(nextdata & nbitsmask); \ nextdata >>= nbits; \ nextbits -= nbits; \ } static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = "LZWDecodeCompat"; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; int code, nbits; long nextbits, nextdata, nbitsmask; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ); tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); return (1); } /* * Residue satisfies only part of the decode request. */ op += residue, occ -= residue; tp = op; do { *--tp = codep->value; codep = codep->next; } while (--residue); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCodeCompat); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask; NextCode(tif, sp, bp, code, GetNextCodeCompat); if (code == CODE_EOI) break; if (code >= CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %d", tif->tif_row); return (0); } *op++ = code, occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded " "string: data probably corrupted at scanline %d", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep->length > occ); sp->dec_restart = occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); break; } assert(occ >= codep->length); op += codep->length, occ -= codep->length; tp = op; do { *--tp = codep->value; } while( (codep = codep->next) != NULL ); } else *op++ = code, occ--; } tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && defined(_MSC_VER) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %I64d bytes)", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %llu bytes)", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); } #endif /* LZW_COMPAT */ #endif /* if 1 */ /* * LZW Encoding. */ static int LZWSetupEncode(TIFF* tif) { //static const char module[] = "LZWSetupEncode"; LZWCodecState* sp = EncoderState(tif); assert(sp != NULL); //sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t)); sp->enc_hashtab = (hash_t*) malloc(HSIZE*sizeof (hash_t)); if (sp->enc_hashtab == NULL) { //TIFFErrorExt(tif->tif_clientdata, module, // "No space for LZW hash table"); return (0); } return (1); } /* * Reset encoding state at the start of a strip. */ static int LZWPreEncode(TIFF* tif/*, uint16 s*/) { LZWCodecState *sp = EncoderState(tif); //(void) s; assert(sp != NULL); if( sp->enc_hashtab == NULL ) { //tif->tif_setupencode( tif ); LZWSetupEncode(tif); } sp->lzw_nbits = BITS_MIN; sp->lzw_maxcode = MAXCODE(BITS_MIN); sp->lzw_free_ent = CODE_FIRST; sp->lzw_nextbits = 0; sp->lzw_nextdata = 0; sp->enc_checkpoint = CHECK_GAP; sp->enc_ratio = 0; sp->enc_incount = 0; sp->enc_outcount = 0; /* * The 4 here insures there is space for 2 max-sized * codes in LZWEncode and LZWPostDecode. */ sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4; cl_hash(sp); /* clear hash table */ sp->enc_oldcode = (hcode_t) -1; /* generates CODE_CLEAR in LZWEncode */ return (1); } #define CALCRATIO(sp, rat) { \ if (incount > 0x007fffff) { /* NB: shift will overflow */\ rat = outcount >> 8; \ rat = (rat == 0 ? 0x7fffffff : incount/rat); \ } else \ rat = (incount<<8) / outcount; \ } #define PutNextCode(op, c) { \ nextdata = (nextdata << nbits) | c; \ nextbits += nbits; \ *op++ = (unsigned char)(nextdata >> (nextbits-8)); \ nextbits -= 8; \ if (nextbits >= 8) { \ *op++ = (unsigned char)(nextdata >> (nextbits-8)); \ nextbits -= 8; \ } \ outcount += nbits; \ } /* * Encode a chunk of pixels. * * Uses an open addressing double hashing (no chaining) on the * prefix code/next character combination. We do a variant of * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's * relatively-prime secondary probe. Here, the modular division * first probe is gives way to a faster exclusive-or manipulation. * Also do block compression with an adaptive reset, whereby the * code table is cleared when the compression ratio decreases, * but after the table fills. The variable-length output codes * are re-sized at this point, and a CODE_CLEAR is generated * for the decoder. */ #define FLUSHDATA(LST, DATA, DATASIZE) { \ npy_intp dims[] = {(DATASIZE)}; \ PyObject *arr = PyArray_EMPTY(1, dims, NPY_UBYTE, 0); \ memcpy(PyArray_DATA((PyArrayObject*)arr), (DATA), dims[0]); \ PyList_Append(lst, arr); \ } static int LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc/*, uint16 s*/ ,PyObject* lst) { register LZWCodecState *sp = EncoderState(tif); register long fcode; register hash_t *hp; register int h, c; hcode_t ent; long disp; long incount, outcount, checkpoint; long nextdata, nextbits; int free_ent, maxcode, nbits; uint8* op; uint8* limit; //(void) s; if (sp == NULL) return (0); assert(sp->enc_hashtab != NULL); /* * Load local state. */ incount = sp->enc_incount; outcount = sp->enc_outcount; checkpoint = sp->enc_checkpoint; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; free_ent = sp->lzw_free_ent; maxcode = sp->lzw_maxcode; nbits = sp->lzw_nbits; op = tif->tif_rawcp; limit = sp->enc_rawlimit; ent = sp->enc_oldcode; if (ent == (hcode_t) -1 && cc > 0) { /* * NB: This is safe because it can only happen * at the start of a strip where we know there * is space in the data buffer. */ PutNextCode(op, CODE_CLEAR); ent = *bp++; cc--; incount++; } while (cc > 0) { c = *bp++; cc--; incount++; fcode = ((long)c << BITS_MAX) + ent; h = (c << HSHIFT) ^ ent; /* xor hashing */ #ifdef _WINDOWS /* * Check hash index for an overflow. */ if (h >= HSIZE) h -= HSIZE; #endif hp = &sp->enc_hashtab[h]; if (hp->hash == fcode) { ent = hp->code; continue; } if (hp->hash >= 0) { /* * Primary hash failed, check secondary hash. */ disp = HSIZE - h; if (h == 0) disp = 1; do { /* * Avoid pointer arithmetic 'cuz of * wraparound problems with segments. */ if ((h -= disp) < 0) h += HSIZE; hp = &sp->enc_hashtab[h]; if (hp->hash == fcode) { ent = hp->code; goto hit; } } while (hp->hash >= 0); } /* * New entry, emit code and add to table. */ /* * Verify there is space in the buffer for the code * and any potential Clear code that might be emitted * below. The value of limit is setup so that there * are at least 4 bytes free--room for 2 codes. */ if (op > limit) { tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); //TIFFFlushData1(tif); FLUSHDATA(lst, tif->tif_rawdata, tif->tif_rawcc); op = tif->tif_rawdata; } PutNextCode(op, ent); ent = c; hp->code = free_ent++; hp->hash = fcode; if (free_ent == CODE_MAX-1) { /* table is full, emit clear code and reset */ cl_hash(sp); sp->enc_ratio = 0; incount = 0; outcount = 0; free_ent = CODE_FIRST; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; maxcode = MAXCODE(BITS_MIN); } else { /* * If the next entry is going to be too big for * the code size, then increase it, if possible. */ if (free_ent > maxcode) { nbits++; assert(nbits <= BITS_MAX); maxcode = (int) MAXCODE(nbits); } else if (incount >= checkpoint) { long rat; /* * Check compression ratio and, if things seem * to be slipping, clear the hash table and * reset state. The compression ratio is a * 24+8-bit fractional number. */ checkpoint = incount+CHECK_GAP; CALCRATIO(sp, rat); if (rat <= sp->enc_ratio) { cl_hash(sp); sp->enc_ratio = 0; incount = 0; outcount = 0; free_ent = CODE_FIRST; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; maxcode = MAXCODE(BITS_MIN); } else sp->enc_ratio = rat; } } hit: ; } /* * Restore global state. */ sp->enc_incount = incount; sp->enc_outcount = outcount; sp->enc_checkpoint = checkpoint; sp->enc_oldcode = ent; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->lzw_free_ent = free_ent; sp->lzw_maxcode = maxcode; sp->lzw_nbits = nbits; tif->tif_rawcp = op; return (1); } /* * Finish off an encoded strip by flushing the last * string and tacking on an End Of Information code. */ static int LZWPostEncode(TIFF* tif, PyObject* lst) { register LZWCodecState *sp = EncoderState(tif); uint8* op = tif->tif_rawcp; long nextbits = sp->lzw_nextbits; long nextdata = sp->lzw_nextdata; long outcount = sp->enc_outcount; int nbits = sp->lzw_nbits; if (op > sp->enc_rawlimit) { tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); //TIFFFlushData1(tif); FLUSHDATA(lst, tif->tif_rawdata, tif->tif_rawcc); op = tif->tif_rawdata; } if (sp->enc_oldcode != (hcode_t) -1) { PutNextCode(op, sp->enc_oldcode); sp->enc_oldcode = (hcode_t) -1; } PutNextCode(op, CODE_EOI); if (nextbits > 0) *op++ = (unsigned char)(nextdata << (8-nextbits)); tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); FLUSHDATA(lst, tif->tif_rawdata, tif->tif_rawcc); return (1); } /* * Reset encoding hash table. */ static void cl_hash(LZWCodecState* sp) { register hash_t *hp = &sp->enc_hashtab[HSIZE-1]; register long i = HSIZE-8; do { i -= 8; hp[-7].hash = -1; hp[-6].hash = -1; hp[-5].hash = -1; hp[-4].hash = -1; hp[-3].hash = -1; hp[-2].hash = -1; hp[-1].hash = -1; hp[ 0].hash = -1; hp -= 8; } while (i >= 0); for (i += 8; i > 0; i--, hp--) hp->hash = -1; } static void LZWCleanup(TIFF* tif) { //(void)TIFFPredictorCleanup(tif); assert(tif->tif_data != 0); if (DecoderState(tif)->dec_codetab) //_TIFFfree(DecoderState(tif)->dec_codetab); free(DecoderState(tif)->dec_codetab); if (EncoderState(tif)->enc_hashtab) //_TIFFfree(EncoderState(tif)->enc_hashtab); free(EncoderState(tif)->enc_hashtab); //_TIFFfree(tif->tif_data); free(tif->tif_data); tif->tif_data = NULL; //_TIFFSetDefaultCompressionState(tif); } #if 0 int TIFFInitLZW(TIFF* tif/*, int scheme*/) { //static const char module[] = "TIFFInitLZW"; //assert(scheme == COMPRESSION_LZW); /* * Allocate state block so tag methods have storage to record values. */ //tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LZWCodecState)); tif->tif_data = (uint8*) malloc(sizeof (LZWCodecState)); if (tif->tif_data == NULL) goto bad; DecoderState(tif)->dec_codetab = NULL; //DecoderState(tif)->dec_decode = NULL; EncoderState(tif)->enc_hashtab = NULL; //LZWState(tif)->rw_mode = tif->tif_mode; /* * Install codec methods. */ /* tif->tif_fixuptags = LZWFixupTags; tif->tif_setupdecode = LZWSetupDecode; tif->tif_predecode = LZWPreDecode; tif->tif_decoderow = LZWDecode; tif->tif_decodestrip = LZWDecode; tif->tif_decodetile = LZWDecode; tif->tif_setupencode = LZWSetupEncode; tif->tif_preencode = LZWPreEncode; tif->tif_postencode = LZWPostEncode; tif->tif_encoderow = LZWEncode; tif->tif_encodestrip = LZWEncode; tif->tif_encodetile = LZWEncode; tif->tif_cleanup = LZWCleanup; */ /* * Setup predictor setup. */ //(void) TIFFPredictorInit(tif); return (1); bad: //TIFFErrorExt(tif->tif_clientdata, module, // "No space for LZW state block"); return (0); } #endif /* if 0 */ static PyObject *py_decode(PyObject *self, PyObject *args, PyObject *kwds) { PyObject* arr = NULL; PyObject* result = NULL; TIFF tif; static char* kwlist[] = {"arr","size",NULL}; long occ; npy_intp dims[] = {0}; PyArray_Dims newshape; if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oi", kwlist, &arr, dims)) return NULL; if (!PyArray_Check(arr)) { PyErr_SetString(PyExc_TypeError,"first argument must be array object"); return NULL; } /* TIFFInitLZW */ tif.tif_data = (uint8*) malloc(sizeof (LZWCodecState)); DecoderState(&tif)->dec_codetab = NULL; //DecoderState(&tif)->dec_decode = NULL; EncoderState(&tif)->enc_hashtab = NULL; //LZWState(&tif)->rw_mode = tif->tif_mode; /* eof TIFFInitLZW */ tif.tif_rawcp = tif.tif_rawdata = (uint8*)PyArray_DATA((PyArrayObject*)arr); tif.tif_rawcc = tif.tif_rawdatasize = PyArray_NBYTES((PyArrayObject*)arr); result = PyArray_EMPTY(1, dims, NPY_UBYTE, 0); if (result!=NULL) { LZWPreDecode(&tif); occ = LZWDecode(&tif, (uint8*)PyArray_DATA((PyArrayObject*)result), PyArray_NBYTES((PyArrayObject*)result)); LZWCleanup(&tif); if (occ>0) { dims[0] -= occ; newshape.ptr = dims; newshape.len = 1; if (PyArray_Resize((PyArrayObject*)result, &newshape, 0, PyArray_CORDER)==NULL) return NULL; } } return result; } static PyObject *py_encode(PyObject *self, PyObject *args, PyObject *kwds) { PyObject* arr = NULL; PyObject* lst = PyList_New(0); PyObject* result = NULL; npy_intp dims[] = {0}; int buffer_size; int i, j; TIFF tif; static char* kwlist[] = {"arr",NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &arr)) return NULL; if (!PyArray_Check(arr)) { PyErr_SetString(PyExc_TypeError,"first argument must be array object"); return NULL; } /* TIFFInitLZW */ tif.tif_data = (uint8*) malloc(sizeof (LZWCodecState)); DecoderState(&tif)->dec_codetab = NULL; //DecoderState(&tif)->dec_decode = NULL; EncoderState(&tif)->enc_hashtab = NULL; //LZWState(&tif)->rw_mode = tif->tif_mode; /* eof TIFFInitLZW */ // create buffer buffer_size = PyArray_NBYTES((PyArrayObject*)arr); if (buffer_size > (1<<20)) buffer_size = (1<<20); tif.tif_rawcp = tif.tif_rawdata = (uint8*)malloc(buffer_size * sizeof(uint8)); tif.tif_rawdatasize = buffer_size; // encode LZWPreEncode(&tif); LZWEncode(&tif, (uint8*)PyArray_DATA((PyArrayObject*)arr), PyArray_NBYTES((PyArrayObject*)arr), lst); LZWPostEncode(&tif, lst); // get result from buffer lst if (PyList_GET_SIZE(lst)==1) { result = PyList_GET_ITEM(lst, 0); Py_INCREF(result); } else { dims[0] = 0; for (i=0; i%s' % (name, func(entry, debug=False))) else: v = entry.value[name] l.append('\n %s=%s' % (name, v)) return 'IFDEntry(tag=%s, value=%s(%s))' % (entry.tag_name, entry.type_name, ', '.join (l)) def IFDEntry_lsm_init_hook(ifdentry): """Make tiff.IFDENTRYEntry CZ_LSM aware. """ global tiff_module_dict if ifdentry.tag==CZ_LSMInfo_tag: # replace type,count=(BYTE,500) with (CZ_LSMInfo, 1) reserved_bytes = (ifdentry.count - CZ_LSMInfo_dtype_fields_size) CZ_LSMInfo_type = (CZ_LSMInfo_tag, reserved_bytes) if CZ_LSMInfo_type not in tiff_module_dict['type2dtype']: dtype = numpy.dtype(CZ_LSMInfo_dtype_fields + [('Reserved', numpy.dtype('(%s,)u4' % (reserved_bytes//4)))]) CZ_LSMInfo_type_name = 'CZ_LSMInfo%s' % (reserved_bytes) CZ_LSMInfo_type_size = dtype.itemsize tiff_module_dict['type2dtype'][CZ_LSMInfo_type] = dtype tiff_module_dict['type2name'][CZ_LSMInfo_type] = CZ_LSMInfo_type_name tiff_module_dict['type2bytes'][CZ_LSMInfo_type] = CZ_LSMInfo_type_size tiff_module_dict['tag_name2value'][CZ_LSMInfo_type_name] = CZ_LSMInfo_tag #assert ifdentry.count==CZ_LSMInfo_type_size,`ifdentry.count,CZ_LSMInfo_type_size` ifdentry.type = CZ_LSMInfo_type ifdentry.count = 1 ifdentry.tiff.is_lsm = True ifdentry.str_hook = IFDEntry_lsm_str_hook else: if not hasattr(ifdentry.tiff, 'is_lsm'): ifdentry.tiff.is_lsm = False def IFDEntry_lsm_finalize_hook(ifdentry): if ifdentry.tag==CZ_LSMInfo_tag: blockstart, blockend = None, None for name in ifdentry.value.dtype.names: func = CZ_LSMOffsetField_readers.get(name) if func is not None: s = func(ifdentry, debug=False) if s is not None: start = s.offset end = start + s.get_size() if blockstart is None: blockstart, blockend = start, end else: blockstart, blockend = min(blockstart,start), max(blockend,end) if verbose_lsm_memory_usage: ifdentry.memory_usage.append((start, end, ifdentry.tag_name+' '+name[6:])) if verbose_lsm_memory_usage: for offset in ifdentry.value['Reserved'][0]: if offset: ifdentry.memory_usage.append((offset, offset, 'start of a unknown reserved field')) else: ifdentry.memory_usage.append((blockstart, blockend, 'lsmblock')) ifdentry.block_range = (blockstart, blockend) ifdentry.tiff.lsminfo = scaninfo(ifdentry, debug=False) ifdentry.tiff.lsmblock = lsmblock(ifdentry, debug=False) ifdentry.tiff.lsmentry = ifdentry.value def register(tiff_dict): """Register CZ_LSM support in tiff module. """ global tiff_module_dict tiff_module_dict = tiff_dict tiff_dict['IFDEntry_init_hooks'].append(IFDEntry_lsm_init_hook) tiff_dict['IFDEntry_finalize_hooks'].append(IFDEntry_lsm_finalize_hook) def lsminfo(ifdentry, new_lsmblock_start=None): if ifdentry.tag!=CZ_LSMInfo_tag: return target = ifdentry.value.copy() old_lsmblock_start = ifdentry.block_range[0] if new_lsmblock_start is None: new_lsmblock_start = old_lsmblock_start offset_diff = new_lsmblock_start - old_lsmblock_start i = 0 for name in ifdentry.value.dtype.names: dt = ifdentry.value.dtype[name] value_ref = target[name] value = value_ref[0] if name.startswith('Offset') and value!=0: #print 'changing',name,'from',value,'to', value_ref += offset_diff #print value_ref[0] elif name=='Reserved': # assuming that unknown values in Reserved field are offsets: for i in range(len(value)): if value[i]!=0: if value[i]>=ifdentry.block_range[0] and value[i]<=ifdentry.block_range[1]: #print 'chaning Reserved[%s] from %s to' % (i, value[i]), value[i] += offset_diff #print value[i] else: sys.stderr.write('Reserved[%s]=%s is out of block range %s. lsminfo might not be correct.' % (i,value[i], ifdentry.block_range)) i += dt.itemsize return target class LSMBlock: def __init__(self, ifdentry): self.ifdentry = ifdentry self._offset = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.block_range[0] return self._offset def get_size(self): return self.ifdentry.block_range[1] - self.offset def __str__(self): return '%s(offset=%s, size=%s, end=%s)' % (self.__class__.__name__, self.offset, self.get_size(), self.offset+self.get_size()) def get_data(self, new_offset): raise NotImplementedError(`new_offset`) def toarray(self, target=None, new_offset=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype = numpy.ubyte) if new_offset is None: new_offset = self.offset offset_diff = new_offset - self.offset dtype = target.dtype target[:sz] = self.ifdentry.tiff.data[self.offset:self.offset + sz] return target def lsmblock(ifdentry, debug=True): if ifdentry.tag!=CZ_LSMInfo_tag: return r = LSMBlock(ifdentry) if debug: arr = r.toarray() offset = r.offset arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class ScanInfoEntry: """ Holds scan information entry data structure. """ def __init__(self, entry, type_name, label, data): self._offset = None self.record = (entry, type_name, label, data) self.footer = None if type_name == 'ASCII': self.type = 2 self.header = numpy.array([entry, 2, len(data)+1], dtype=numpy.uint32).view(dtype=numpy.ubyte) elif type_name == 'LONG': self.type = 4 self.header = numpy.array([entry, 4, 4], dtype=numpy.uint32).view(dtype=numpy.ubyte) elif type_name == 'DOUBLE': self.type = 5 self.header = numpy.array([entry, 5, 8], dtype=numpy.uint32).view(dtype=numpy.ubyte) elif type_name == 'SUBBLOCK': self.type = 0 self.header = numpy.array([entry, 0, 0], dtype=numpy.uint32).view(dtype=numpy.ubyte) else: raise NotImplementedError (`self.record`) def __repr__ (self): return '%s%r' % (self.__class__.__name__, self.record) @property def is_subblock(self): return self.record[1]=='SUBBLOCK' @property def label(self): return self.record[2] @property def data(self): return self.record[3] def get(self, label): if self.label == label: if self.is_subblock: return self return self.data if self.is_subblock and self.data is not None: l = [] for entry in self.data: r = entry.get(label) if isinstance(r, list): l.extend(r) elif r is not None: l.append(r) if not l: return return l @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value['OffsetScanInformation'][0] return self._offset def get_size(self): """ Return total memory size in bytes needed to fit the entry to memory. """ (entry, type_name, label, data) = self.record if type_name=='SUBBLOCK': if data is None: return 12 size = 0 for item in data: size += item.get_size() return 12 + size if type_name=='LONG': return 12 + 4 if type_name=='DOUBLE': return 12 + 8 if type_name == 'ASCII': return 12 + len(data) + 1 raise NotImplementedError (`self.record`) def toarray(self, target = None): if target is None: target = numpy.zeros((self.get_size(),), dtype=numpy.ubyte) dtype = target.dtype (entry, type_name, label, data) = self.record target[:12] = self.header if type_name=='SUBBLOCK': if data is not None: n = 12 for item in data: item.toarray(target[n:]) n += item.get_size() elif type_name == 'ASCII': target[12:12+len(data)+1] = numpy.array([data+'\0']).view(dtype=dtype) elif type_name == 'LONG': target[12:12+4] = numpy.array([data], dtype=numpy.uint32).view(dtype=dtype) elif type_name == 'DOUBLE': target[12:12+8] = numpy.array([data], dtype=numpy.float64).view(dtype=dtype) else: raise NotImplementedError (`self.record`) return target def tostr(self, tab='', short=False): (entry, type_name, label, data) = self.record if hasattr(self, 'parent') and self.parent is not None: parent_label = self.parent.record[2] else: parent_label = '' if type_name=='SUBBLOCK': if data is None: return '%s%s %s' % (tab[:-2], label, parent_label) l = ['%s%s[size=%s]' % (tab, label, self.get_size ())] for item in data: if not short or item.data: l.append(item.tostr(tab=tab+' ', short=short)) return '\n'.join (l) if label.startswith(parent_label): label = label[len(parent_label):] return '%s%s = %r' % (tab, label, data) __str__ = tostr def append (self, entry): assert self.record[1]=='SUBBLOCK',`self.record` self.record[3].append(entry) def scaninfo(ifdentry, debug=True): """ Return LSM scan information. Parameters ---------- ifdentry : IFDEntry debug: bool Enable consistency checks. Returns ------- record : ScanInfoEntry """ if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm n = n1 = ifdentry.value['OffsetScanInformation'][0] if not n: return record = None tab = ' ' while 1: entry, type, size = ifdentry.tiff.get_values(n, 'LONG', 3) n += 12 label, type_name = scaninfo_map.get(entry, (None, None)) if label is None: type_name = {0:'SUBBLOCK', 2:'ASCII', 4:'LONG', 5:'DOUBLE'}.get(type) if type_name is None: raise NotImplementedError(`hex (entry), type, size`) label = 'ENTRY%s' % (hex(entry)) #scaninfo_map[entry] = label, type_name if debug: sys.stderr.write('lsm.scaninfo: undefined %s entry %s in subblock %r\n'\ % (type_name, hex(entry), record.record[2])) pass if type_name=='SUBBLOCK': assert type==0,`hex (entry), type, size` if label == 'end': entry = ScanInfoEntry(entry, type_name, label, None) entry.parent = record record.append(entry) if record.parent is None: break record.parent.append(record) record = record.parent else: prev_record = record record = ScanInfoEntry(entry, type_name, label, []) record.parent = prev_record assert size==0,`hex (entry), type, size` continue if type_name=='ASCII': assert type==2,`hex (entry), type, size` value = ifdentry.tiff.get_string (n, size-1) elif type_name=='LONG': assert type==4,`hex (entry), type, size, scaninfo_map[entry]` value = ifdentry.tiff.get_long(n) elif type_name=='DOUBLE': assert type==5,`hex (entry), type, size` value = ifdentry.tiff.get_double(n) else: raise NotImplementedError(`type_name, hex (entry), type, size`) entry = ScanInfoEntry(entry, type_name, label, value) entry.parent = record n += size record.append(entry) if debug: size = n - n1 record_size = record.get_size() assert size==record_size,`size,record_size` arr = record.toarray() arr2 = ifdentry.tiff.data[n1:n1+size] assert (arr==arr2).all() record.offset = n1 return record class TimeStamps: """ Holds LSM time stamps information. """ def __init__(self, ifdentry): self.ifdentry = ifdentry self._offset = None self._header = None self._stamps = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value['OffsetTimeStamps'][0] return self._offset @property def header(self): if self._header is None: offset = self.offset self._header = self.ifdentry.tiff.get_value(offset, CZ_LSMTimeStamps_header_dtype) return self._header @property def stamps(self): if self._stamps is None: n = self.header['NumberTimeStamps'] self._stamps = self.ifdentry.tiff.get_values(self.offset + self.header.dtype.itemsize, numpy.float64, int(n)) return self._stamps def __str__(self): return '%s(stamps=%s)' % (self.__class__.__name__, self.stamps) def get_size(self): return 8+self.stamps.nbytes def toarray(self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype header = numpy.array([sz, self.stamps.size], dtype=numpy.int32).view(dtype=dtype) assert header.nbytes==8,`header.nbytes` data = self.stamps.view(dtype=dtype) target[:header.nbytes] = header target[header.nbytes:header.nbytes+data.nbytes] = data return target def timestamps(ifdentry, debug=True): """ Return LSM time stamp information. """ if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value['OffsetTimeStamps'][0] if not offset: return None r = TimeStamps(ifdentry) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class EventEntry: def __init__ (self, entry_size, time, event_type, unknown, description): self.record = entry_size, time, event_type, unknown, description @property def time (self): return self.record[1] @property def type (self): return self.record[2] @property def type_name (self): r = {0:'marker', 1:'timer change', 2:'cleach start', 3:'bleach stop', 4:'trigger'}.get (self.type) if r is None: r = 'EventType%s' % (self.type) return r @property def description(self): return self.record[4] def __str__(self): return 'EventEntry(time=%r, type=%r, description=%r)' % (self.time, self.type_name, self.description) def get_size(self): return 4+8+4+4+len(self.description)+1 def toarray (self, target = None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype target[:4].view(dtype=numpy.uint32)[0] = sz target[4:4+8].view(dtype=numpy.float64)[0] = self.time target[12:16].view (dtype=numpy.uint32)[0] = self.type target[16:20].view (dtype=numpy.uint32)[0] = self.record[3] l = len (self.description) target[20:20+l] = numpy.array([self.description]).view(dtype=dtype) target[20+l] = 0 return target class EventList: """ Holds LSM event list information. """ def __init__(self, ifdentry): self.ifdentry = ifdentry self._offset = None self._header = None self._events = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value['OffsetEventList'][0] return self._offset @property def header(self): if self._header is None: self._header = self.ifdentry.tiff.get_value(self.offset, CZ_LSMEventList_header_dtype) return self._header @property def events(self): if self._events is None: n = self.header['NumberEvents'] offset = self.offset + self.header.nbytes self._events = [] for i in range(n): entry_size = self.ifdentry.tiff.get_value (offset, numpy.uint32) time = self.ifdentry.tiff.get_value(offset+4, numpy.float64) event_type = self.ifdentry.tiff.get_value(offset + 4+8, numpy.uint32) unknown = self.ifdentry.tiff.get_value(offset + 4+8+4, numpy.uint32) descr = self.ifdentry.tiff.get_string(offset + 4+8+4+4) self._events.append(EventEntry(entry_size, time, event_type, unknown, descr)) offset += entry_size return self._events def __str__ (self): return '%s(events=[%s])' % (self.__class__.__name__, ','.join(map(str,self.events))) def get_size(self): s = self.header.nbytes for event in self.events: s += event.get_size() return s def toarray (self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype header = numpy.array([sz, len (self.events)], dtype=numpy.int32).view(dtype=dtype) target[:header.nbytes] = header offset = header.nbytes for event in self.events: event.toarray(target[offset:]) offset += event.get_size() return target def eventlist(ifdentry, debug=True): """ Return LSM event list information. """ if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value['OffsetEventList'][0] if not offset: return None r = EventList(ifdentry) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class ChannelWavelength: """ Holds LSM channel wavelength information. """ def __init__ (self, ifdentry): self.ifdentry = ifdentry self._offset = None self._ranges = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value['OffsetChannelWavelength'][0] return self._offset @property def ranges (self): if self._ranges is None: self._ranges = [] offset = self.offset n = self.ifdentry.tiff.get_value (offset, numpy.int32) for i in range(n): start, end = self.ifdentry.tiff.get_values(offset + 4 + i*(8+8), numpy.float64, 2) self._ranges.append((start, end)) return self._ranges def __str__ (self): return '%s (ranges=%s)' % (self.__class__.__name__, self.ranges) def get_size(self): return 4 + len(self.ranges)*16 def toarray (self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype target[:4].view(dtype=numpy.int32)[0] = len(self.ranges) data = numpy.array(self.ranges).ravel() target[4:4+data.nbytes] = data.view (dtype=dtype) return target def channelwavelength(ifdentry, debug=True): """ Return LSM wavelength range information. """ if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value['OffsetChannelWavelength'][0] if not offset: return None r = ChannelWavelength(ifdentry) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class ChannelColors: """ Holds LSM channel name and color information. """ def __init__ (self, ifdentry): self.ifdentry = ifdentry self._offset = None self._header = None self._names = None self._colors = None self._mono = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value['OffsetChannelColors'][0] return self._offset @property def mono (self): if self._mono is None: self._mono = not not self.header[5] return self._mono @property def header (self): if self._header is None: self._header = self.ifdentry.tiff.get_values(self.offset, numpy.int32, 10) sz = self._header[0] return self._header @property def names(self): if self._names is None: header = self.header n = header[2] offset = self.offset + header[4] + 4 self._names = [] for i in range(n): name = self.ifdentry.tiff.get_string(offset) offset += len(name) + 1 + 4 self._names.append(name) return self._names @property def colors(self): if self._colors is None: header = self.header n = header[1] offset = self.offset + header[3] self._colors = [] for i in range(n): color = self.ifdentry.tiff.get_values(offset, numpy.uint8, 4) offset += color.nbytes self._colors.append(tuple(color)) return self._colors def __str__(self): return '%s (names=%s, colors=%s)' % (self.__class__.__name__, self.names, self.colors) def get_size(self): s = 10*4 for name in self.names: s += len(name) + 1 + 4 for color in self.colors: s += len(color) return s def toarray (self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype header = numpy.array([sz,len (self.colors), len (self.names), 0, 0, self.mono, 0,0,0,0], dtype=numpy.int32) names = '' for name in self.names: names += '\x04\0\0\0' + name + '\x00' noffset = sz - len(names) names = numpy.array([names]).view (dtype=dtype) colors = numpy.array (self.colors, dtype=numpy.uint8).ravel() coffset = noffset - colors.nbytes header[3] = coffset header[4] = noffset target[:header.nbytes] = header.view(dtype=dtype) target[coffset:coffset + colors.nbytes] = colors target[noffset:noffset + names.nbytes] = names return target def channelcolors(ifdentry, debug=True): """ Return LSM channel name and color information. """ if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value['OffsetChannelColors'][0] if not offset: return None r = ChannelColors(ifdentry) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class ChannelFactors: def __init__(self, ifdentry): self.ifdentry = ifdentry self._offset = None self._data = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value['OffsetChannelFactors'][0] return self._offset @property def data(self): if self._data is None: n = self.ifdentry.tiff.get_value(self.offset, numpy.int32) sz = 4 + n # n should be equal to 32*nofchannels self._data = self.ifdentry.tiff.get_values(self.offset, numpy.ubyte, sz) return self._data def __str__(self): return '%s(size=%r, offset=%r)' % (self.__class__.__name__, self.get_size(), self.offset) def get_size(self): return self.data.nbytes def toarray(self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype target[:self.data.nbytes] = self.data.view(dtype=dtype) return target def channelfactors(ifdentry, debug=True): if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value['OffsetChannelFactors'][0] if not offset: return r = ChannelFactors(ifdentry) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class ChannelDataTypes: def __init__(self, ifdentry): self.ifdentry = ifdentry self._offset = None self._data = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value['OffsetChannelDataTypes'][0] return self._offset @property def data(self): if self._data is None: channels = self.ifdentry.value['DimensionChannels'] sz = channels * 4 self._data = self.ifdentry.tiff.get_values(self.offset, numpy.ubyte, sz) return self._data def __str__(self): return '%s(size=%r, offset=%r)' % (self.__class__.__name__, self.get_size(), self.offset) def get_size(self): return self.data.nbytes def toarray(self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype target[:self.data.nbytes] = self.data.view(dtype=dtype) return target def channeldatatypes(ifdentry, debug=True): if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value['OffsetChannelDataTypes'][0] if not offset: return r = ChannelDataTypes(ifdentry) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class OffsetData: def __init__(self, ifdentry, offset_name): self.ifdentry = ifdentry self.offset_name = offset_name self._offset = None self._data = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value[self.offset_name][0] return self._offset @property def data(self): if self._data is None: sz = self.ifdentry.tiff.get_value(self.offset, numpy.uint32) self._data = self.ifdentry.tiff.get_values(self.offset, numpy.ubyte, sz) return self._data def __str__(self): return '%s(name=%r, size=%r, offset=%r)' % (self.__class__.__name__, self.offset_name, self.get_size(), self.offset) def get_size(self): return self.data.nbytes def toarray(self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype target[:self.data.nbytes] = self.data.view(dtype=dtype) return target def offsetdata(ifdentry, offset_name, debug=True): if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value[offset_name][0] if not offset: return r = OffsetData(ifdentry, offset_name) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class DrawingElement: def __init__(self, ifdentry, offset_name): self.ifdentry = ifdentry self.offset_name = offset_name self._offset = None self._data = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value[self.offset_name][0] return self._offset @property def data(self): if self._data is None: n = self.ifdentry.tiff.get_value(self.offset, numpy.int32) sz = self.ifdentry.tiff.get_value(self.offset+4, numpy.int32) self._data = self.ifdentry.tiff.get_values(self.offset, numpy.ubyte, sz) return self._data def __str__(self): return '%s(name=%r, size=%r, offset=%r)' % (self.__class__.__name__, self.offset_name, self.get_size(), self.offset) def get_size(self): return self.data.nbytes def toarray(self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype target[:self.data.nbytes] = self.data.view(dtype=dtype) return target def drawingelement(ifdentry, offset_name, debug=True): if ifdentry.tag!=CZ_LSMInfo_tag: return #assert ifdentry.is_lsm offset = ifdentry.value[offset_name][0] if not offset: return r = DrawingElement(ifdentry, offset_name) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r class LookupTable: def __init__(self, ifdentry, offset_name): self.ifdentry = ifdentry self.offset_name = offset_name self._offset = None self._data = None @property def offset(self): if self._offset is None: self._offset = self.ifdentry.value[self.offset_name][0] return self._offset @property def data(self): if self._data is None: sz = self.ifdentry.tiff.get_value(self.offset, numpy.uint32) self._data = self.ifdentry.tiff.get_values(self.offset, numpy.ubyte, sz) return self._data def __str__(self): nsubblocks = self.ifdentry.tiff.get_value(self.offset+4, numpy.uint32) nchannels = self.ifdentry.tiff.get_value(self.offset+8, numpy.uint32) return '%s(name=%r, size=%r, subblocks=%r, channels=%r, offset=%r)' \ % (self.__class__.__name__, self.offset_name, self.get_size(), nsubblocks, nchannels, self.offset) def get_size(self): return self.data.nbytes def toarray(self, target=None): sz = self.get_size() if target is None: target = numpy.zeros((sz,), dtype=numpy.ubyte) dtype = target.dtype target[:self.data.nbytes] = self.data.view(dtype=dtype) return target def lookuptable(ifdentry, offset_name, debug=True): if ifdentry.tag!=CZ_LSMInfo_tag: return offset = ifdentry.value[offset_name][0] if not offset: return r = LookupTable(ifdentry, offset_name) if debug: arr = r.toarray() arr2 = ifdentry.tiff.data[offset:offset+arr.nbytes] assert (arr==arr2).all() return r inputlut = lambda ifdentry, debug=True: lookuptable(ifdentry, 'OffsetInputLut', debug=debug) outputlut = lambda ifdentry, debug=True: lookuptable(ifdentry, 'OffsetOutputLut', debug=debug) vectoroverlay = lambda ifdentry, debug=True: drawingelement(ifdentry, 'OffsetVectorOverlay', debug=debug) roi = lambda ifdentry, debug=True: drawingelement(ifdentry, 'OffsetRoi', debug=debug) bleachroi = lambda ifdentry, debug=True: drawingelement(ifdentry, 'OffsetBleachRoi', debug=debug) meanofroisoverlay = lambda ifdentry, debug=True: drawingelement(ifdentry, 'OffsetMeanOfRoisOverlay', debug=debug) topoisolineoverlay = lambda ifdentry, debug=True: drawingelement(ifdentry, 'OffsetTopoIsolineOverlay', debug=debug) topoprofileoverlay = lambda ifdentry, debug=True: drawingelement(ifdentry, 'OffsetTopoProfileOverlay', debug=debug) linescanoverlay = lambda ifdentry, debug=True: drawingelement(ifdentry, 'OffsetLinescanOverlay', debug=debug) CZ_LSMOffsetField_readers = dict( OffsetChannelWavelength = channelwavelength, OffsetTimeStamps=timestamps, OffsetEventList=eventlist, OffsetChannelColors = channelcolors, OffsetScanInformation = scaninfo, OffsetInputLut = inputlut, OffsetOutputLut = outputlut, OffsetChannelFactors = channelfactors, OffsetChannelDataTypes = channeldatatypes, OffsetUnmixParameters = lambda ifdentry, debug=True: offsetdata(ifdentry, 'OffsetUnmixParameters', debug=debug), OffsetNextRecording = lambda ifdentry, debug=True: offsetdata(ifdentry, 'OffsetNextRecording', debug=debug), OffsetKsData = lambda ifdentry, debug=True: offsetdata(ifdentry, 'OffsetKsData', debug=debug), OffsetVectorOverlay = vectoroverlay, OffsetRoi = roi, OffsetBleachRoi = bleachroi, OffsetMeanOfRoisOverlay = meanofroisoverlay, OffsetTopoIsolineOverlay = topoisolineoverlay, OffsetTopoProfileOverlay = topoprofileoverlay, OffsetLinescanOverlay = linescanoverlay, ) CZ_LSMInfo_dtype_fields = [ ('MagicNumber',numpy.uint32), ('StructureSize',numpy.int32), ('DimensionX',numpy.int32), ('DimensionY',numpy.int32), ('DimensionZ',numpy.int32), ('DimensionChannels', numpy.int32), ('DimensionTime', numpy.int32), ('SDataType', numpy.int32), # 1: uint8, 2: uint12, 5: float32, 0: see OffsetChannelDataTypes ('ThumbnailX', numpy.int32), ('ThumbnailY', numpy.int32), ('VoxelSizeX', numpy.float64), ('VoxelSizeY', numpy.float64), ('VoxelSizeZ', numpy.float64), ('OriginX', numpy.float64), ('OriginY', numpy.float64), ('OriginZ', numpy.float64), ('ScanType', numpy.uint16), # 0:xyz-scan, 1:z-scan, 2:line-scan 3:time xy, # 4: time xz (ver>=2.0), 5: time mean roi (ver>=2.0), # 6: time xyz (ver>=2.3), 7: spline scan (ver>=2.5), # 8: spline plane xz (ver>=2.5) # 9: time spline plane xz (ver>=2.5) # 10: point mode (ver>=3.0) ('SpectralScan', numpy.uint16), # 0:off, 1:on (ver>=3.0) ('DataType',numpy.uint32), # 0: original, 1: calculated, 2: animation ('OffsetVectorOverlay', numpy.uint32), ('OffsetInputLut',numpy.uint32), ('OffsetOutputLut',numpy.uint32), ('OffsetChannelColors',numpy.uint32), ('TimeInterval',numpy.float64), ('OffsetChannelDataTypes',numpy.uint32), ('OffsetScanInformation',numpy.uint32), ('OffsetKsData',numpy.uint32), ('OffsetTimeStamps',numpy.uint32), ('OffsetEventList',numpy.uint32), ('OffsetRoi',numpy.uint32), ('OffsetBleachRoi',numpy.uint32), ('OffsetNextRecording',numpy.uint32), ('DisplayAspectX',numpy.float64), ('DisplayAspectY',numpy.float64), ('DisplayAspectZ',numpy.float64), ('DisplayAspectTime',numpy.float64), ('OffsetMeanOfRoisOverlay',numpy.uint32), ('OffsetTopoIsolineOverlay', numpy.uint32), ('OffsetTopoProfileOverlay', numpy.uint32), ('OffsetLinescanOverlay', numpy.uint32), ('ToolbarFlags', numpy.uint32), ('OffsetChannelWavelength', numpy.uint32), ('OffsetChannelFactors', numpy.uint32), ('ObjectiveSphereCorrection',numpy.float64), ('OffsetUnmixParameters',numpy.uint32), #('Reserved', numpy.dtype('(69,)u4')), # depends on the version of LSM file ] CZ_LSMInfo_dtype_fields_size = 0 for item in CZ_LSMInfo_dtype_fields: CZ_LSMInfo_dtype_fields_size += item[1]().itemsize CZ_LSMTimeStamps_header_dtype = numpy.dtype([ ('Size', numpy.int32), ('NumberTimeStamps', numpy.int32), # ('TimeStamp', numpy.float64) ]) CZ_LSMEventList_header_dtype = numpy.dtype ([ ('Size', numpy.int32), ('NumberEvents', numpy.int32), # ('Event', EventListEntry) ]) scaninfo_map = { 0x0ffffffff: ( 'end', 'SUBBLOCK'), 0x010000000: ( 'recording','SUBBLOCK'), 0x010000001: ( 'recording name','ASCII'), 0x010000002: ( 'recording description','ASCII'), 0x010000003: ( 'recording notes','ASCII'), 0x010000004: ( 'recording objective','ASCII'), 0x010000005: ( 'recording processing summary','ASCII'), 0x010000006: ( 'recording special scan mode','ASCII'), 0x010000007: ( 'recording scan type','ASCII'), 0x010000008: ( 'recording scan mode','ASCII'), 0x010000009: ( 'recording number of stacks','LONG'), 0x01000000a: ( 'recording lines per plane','LONG'), 0x01000000b: ( 'recording samples per line','LONG'), 0x01000000c: ( 'recording planes per volume','LONG'), 0x01000000d: ( 'recording images width','LONG'), 0x01000000e: ( 'recording images height','LONG'), 0x01000000f: ( 'recording images number planes','LONG'), 0x010000010: ( 'recording images number stacks','LONG'), 0x010000011: ( 'recording images number channels','LONG'), 0x010000012: ( 'recording linescan xy size','LONG'), 0x010000013: ( 'recording scan direction','LONG'), 0x010000014: ( 'recording time series','LONG'), 0x010000015: ( 'recording original scan data','LONG'), 0x010000016: ( 'recording zoom x','DOUBLE'), 0x010000017: ( 'recording zoom y','DOUBLE'), 0x010000018: ( 'recording zoom z','DOUBLE'), 0x010000019: ( 'recording sample 0x','DOUBLE'), 0x01000001a: ( 'recording sample 0y','DOUBLE'), 0x01000001b: ( 'recording sample 0z','DOUBLE'), 0x01000001c: ( 'recording sample spacing','DOUBLE'), 0x01000001d: ( 'recording line spacing','DOUBLE'), 0x01000001e: ( 'recording plane spacing','DOUBLE'), 0x01000001f: ( 'recording plane width','DOUBLE'), 0x010000020: ( 'recording plane height','DOUBLE'), 0x010000021: ( 'recording volume depth','DOUBLE'), #0x010000022: ( 'recording ',''), 0x010000023: ( 'recording nutation','DOUBLE'), #0x010000024: ( 'recording ',''), #0x010000025: ( 'recording ',''), #0x010000026: ( 'recording ',''), #0x010000027: ( 'recording ',''), #0x010000028: ( 'recording ',''), #0x010000029: ( 'recording ',''), #0x01000002a: ( 'recording ',''), #0x01000002b: ( 'recording ',''), #0x01000002c: ( 'recording ',''), #0x01000002d: ( 'recording ',''), #0x01000002e: ( 'recording ',''), #0x01000002f: ( 'recording ',''), #0x010000030: ( 'recording ',''), #0x010000031: ( 'recording ',''), #0x010000032: ( 'recording ',''), #0x010000033: ( 'recording ',''), 0x010000034: ( 'recording rotation','DOUBLE'), 0x010000035: ( 'recording precession','DOUBLE'), 0x010000036: ( 'recording sample 0time','DOUBLE'), 0x010000037: ( 'recording start scan trigger in','ASCII'), 0x010000038: ( 'recording start scan trigger out','ASCII'), 0x010000039: ( 'recording start scan event','LONG'), #0x01000003a: ( 'recording ',''), #0x01000003b: ( 'recording ',''), #0x01000003c: ( 'recording ',''), #0x01000003d: ( 'recording ',''), #0x01000003e: ( 'recording ',''), #0x01000003f: ( 'recording ',''), 0x010000040: ( 'recording start scan time','DOUBLE'), 0x010000041: ( 'recording stop scan trigger in','ASCII'), 0x010000042: ( 'recording stop scan trigger out','ASCII'), 0x010000043: ( 'recording stop scan event','LONG'), 0x010000044: ( 'recording start scan time','DOUBLE'), 0x010000045: ( 'recording use rois','LONG'), 0x010000046: ( 'recording use reduced memory rois','LONG'), 0x010000047: ( 'recording user','ASCII'), 0x010000048: ( 'recording usebccorrection','LONG'), 0x010000049: ( 'recording positionbccorrection1','DOUBLE'), #0x01000004a: ( 'recording ',''), #0x01000004b: ( 'recording ',''), #0x01000004c: ( 'recording ',''), #0x01000004d: ( 'recording ',''), #0x01000004e: ( 'recording ',''), #0x01000004f: ( 'recording ',''), 0x010000050: ( 'recording positionbccorrection2','DOUBLE'), 0x010000051: ( 'recording interpolationy','LONG'), 0x010000052: ( 'recording camera binning','LONG'), 0x010000053: ( 'recording camera supersampling','LONG'), 0x010000054: ( 'recording camera frame width','LONG'), 0x010000055: ( 'recording camera frame height','LONG'), 0x010000056: ( 'recording camera offsetx','DOUBLE'), 0x010000057: ( 'recording camera offsety','DOUBLE'), #0x010000058: ( 'recording ',''), 0x010000059: ( 'recording rt binning','LONG'), 0x01000005a: ( 'recording rt frame width','LONG'), 0x01000005b: ( 'recording rt frame height','LONG'), 0x01000005c: ( 'recording rt region width','LONG'), 0x01000005d: ( 'recording rt region height','LONG'), 0x01000005e: ( 'recording rt offsetx','DOUBLE'), 0x01000005f: ( 'recording rt offsety','DOUBLE'), 0x010000060: ( 'recording rt zoom','DOUBLE'), 0x010000061: ( 'recording rt lineperiod','DOUBLE'), 0x010000062: ( 'recording prescan','LONG'), 0x010000063: ( 'recording scan directionz','LONG'), #0x010000064: ( 'recording ','LONG'), 0x030000000: ( 'lasers','SUBBLOCK'), 0x050000000: ( 'laser','SUBBLOCK'), 0x050000001: ( 'laser name','ASCII'), 0x050000002: ( 'laser acquire','LONG'), 0x050000003: ( 'laser power','DOUBLE'), 0x020000000: ( 'tracks','SUBBLOCK'), 0x040000000: ( 'track','SUBBLOCK'), 0x040000001: ( 'track multiplex type','LONG'), 0x040000002: ( 'track multiplex order','LONG'), 0x040000003: ( 'track sampling mode','LONG'), 0x040000004: ( 'track sampling method','LONG'), 0x040000005: ( 'track sampling number','LONG'), 0x040000006: ( 'track acquire','LONG'), 0x040000007: ( 'track sample observation time','DOUBLE'), # 0x04000000b: ( 'track time between stacks','DOUBLE'), 0x04000000c: ( 'track name','ASCII'), 0x04000000d: ( 'track collimator1 name','ASCII'), 0x04000000e: ( 'track collimator1 position','LONG'), 0x04000000f: ( 'track collimator2 name','ASCII'), 0x040000010: ( 'track collimator2 position','LONG'), 0x040000011: ( 'track is bleach track','LONG'), 0x040000012: ( 'track is bleach after scan number','LONG'), 0x040000013: ( 'track bleach scan number','LONG'), 0x040000014: ( 'track trigger in','ASCII'), 0x040000015: ( 'track trigger out','ASCII'), 0x040000016: ( 'track is ratio track','LONG'), 0x040000017: ( 'track bleach count','LONG'), 0x040000018: ( 'track spi center wavelength','DOUBLE'), 0x040000019: ( 'track pixel time','DOUBLE'), 0x040000020: ( 'track id condensor frontlens','ASCII'), 0x040000021: ( 'track condensor frontlens','LONG'), 0x040000022: ( 'track id field stop','ASCII'), 0x040000023: ( 'track field stop value','DOUBLE'), 0x040000024: ( 'track id condensor aperture','ASCII'), 0x040000025: ( 'track condensor aperture','DOUBLE'), 0x040000026: ( 'track id condensor revolver','ASCII'), 0x040000027: ( 'track condensor filter','ASCII'), 0x040000028: ( 'track id transmission filter1','ASCII'), 0x040000029: ( 'track id transmission1','DOUBLE'), 0x040000030: ( 'track id transmission filter2','ASCII'), 0x040000031: ( 'track if transmission2','DOUBLE'), 0x040000032: ( 'track repeat bleach','LONG'), 0x040000033: ( 'track enable spot bleach pos','LONG'), 0x040000034: ( 'track spot bleach posx','DOUBLE'), 0x040000035: ( 'track spot bleach posy','DOUBLE'), 0x040000036: ( 'track bleach position z','DOUBLE'), 0x040000037: ( 'track id tubelens','ASCII'), 0x040000038: ( 'track id tubelens position','ASCII'), 0x040000039: ( 'track transmitted light','DOUBLE'), 0x04000003a: ( 'track reflected light','DOUBLE'), 0x04000003b: ( 'track simultan grab and bleach','LONG'), 0x04000003c: ( 'track bleach pixel time','DOUBLE'), 0x060000000: ( 'detection channels','SUBBLOCK'), 0x070000000: ( 'detection channel','SUBBLOCK'), 0x070000001: ( 'detection channel integration mode','LONG'), 0x070000002: ( 'detection channel special mode','LONG'), 0x070000003: ( 'detection channel detector gain first','DOUBLE'), 0x070000004: ( 'detection channel detector gain last','DOUBLE'), 0x070000005: ( 'detection channel amplifier gain first','DOUBLE'), 0x070000006: ( 'detection channel amplifier gain last','DOUBLE'), 0x070000007: ( 'detection channel amplifier offs first','DOUBLE'), 0x070000008: ( 'detection channel amplifier offs last','DOUBLE'), 0x070000009: ( 'detection channel pinhole diameter','DOUBLE'), 0x07000000a: ( 'detection channel counting trigger','DOUBLE'), 0x07000000b: ( 'detection channel acquire','LONG'), 0x07000000c: ( 'detection channel detector name','ASCII'), 0x07000000d: ( 'detection channel amplifier name','ASCII'), 0x07000000e: ( 'detection channel pinhole name','ASCII'), 0x07000000f: ( 'detection channel filter set name','ASCII'), 0x070000010: ( 'detection channel filter name','ASCII'), 0x070000013: ( 'detection channel integrator name','ASCII'), 0x070000014: ( 'detection channel detection channel name','ASCII'), 0x070000015: ( 'detection channel detector gain bc1','DOUBLE'), 0x070000016: ( 'detection channel detector gain bc2','DOUBLE'), 0x070000017: ( 'detection channel amplifier gain bc1','DOUBLE'), 0x070000018: ( 'detection channel amplifier gain bc2','DOUBLE'), 0x070000019: ( 'detection channel amplifier offs bc1','DOUBLE'), 0x070000020: ( 'detection channel amplifier offs bc2','DOUBLE'), 0x070000021: ( 'detection channel spectral scan channels','LONG'), 0x070000022: ( 'detection channel spi wavelength start','DOUBLE'), 0x070000023: ( 'detection channel spi wavelength end','DOUBLE'), 0x070000026: ( 'detection channel dye name','ASCII'), 0x070000027: ( 'detection channel dye folder','ASCII'), 0x080000000: ( 'illumination channels','SUBBLOCK'), 0x090000000: ( 'illumination channel','SUBBLOCK'), 0x090000001: ( 'illumination channel name','ASCII'), 0x090000002: ( 'illumination channel power','DOUBLE'), 0x090000003: ( 'illumination channel wavelength','DOUBLE'), 0x090000004: ( 'illumination channel aquire','LONG'), 0x090000005: ( 'illumination channel detection channel name','ASCII'), 0x090000006: ( 'illumination channel power bc1','DOUBLE'), 0x090000007: ( 'illumination channel power bc2','DOUBLE'), 0x0A0000000: ( 'beam splitters','SUBBLOCK'), 0x0B0000000: ( 'beam splitter','SUBBLOCK'), 0x0B0000001: ( 'beam splitter filter set','ASCII'), 0x0B0000002: ( 'beam splitter filter','ASCII'), 0x0B0000003: ( 'beam splitter name','ASCII'), 0x0C0000000: ( 'data channels','SUBBLOCK'), 0x0D0000000: ( 'data channel','SUBBLOCK'), 0x0D0000001: ( 'data channel name','ASCII'), #0x0D0000002: ( 'data channel',''), 0x0D0000003: ( 'data channel acquire','LONG'), 0x0D0000004: ( 'data channel color','LONG'), 0x0D0000005: ( 'data channel sampletype','LONG'), 0x0D0000006: ( 'data channel bitspersample','LONG'), 0x0D0000007: ( 'data channel ratio type','LONG'), 0x0D0000008: ( 'data channel ratio track1','LONG'), 0x0D0000009: ( 'data channel ratio track2','LONG'), 0x0D000000a: ( 'data channel ratio channel1','ASCII'), 0x0D000000b: ( 'data channel ratio channel2','ASCII'), 0x0D000000c: ( 'data channel ratio const1','DOUBLE'), 0x0D000000d: ( 'data channel ratio const2','DOUBLE'), 0x0D000000e: ( 'data channel ratio const3','DOUBLE'), 0x0D000000f: ( 'data channel ratio const4','DOUBLE'), 0x0D0000010: ( 'data channel ratio const5','DOUBLE'), 0x0D0000011: ( 'data channel ratio const6','DOUBLE'), 0x0D0000012: ( 'data channel ratio first images1','LONG'), 0x0D0000013: ( 'data channel ratio first images2','LONG'), 0x0D0000014: ( 'data channel dye name','ASCII'), 0x0D0000015: ( 'data channel dye folder','ASCII'), 0x0D0000016: ( 'data channel spectrum','ASCII'), 0x0D0000017: ( 'data channel acquire','LONG'), 0x011000000: ( 'timers','SUBBLOCK'), 0x012000000: ( 'timer','SUBBLOCK'), 0x012000001: ( 'timer name','ASCII'), 0x012000003: ( 'timer interval','DOUBLE'), 0x012000004: ( 'timer trigger in','ASCII'), 0x012000005: ( 'timer trigger out','ASCII'), 0x012000006: ( 'timer activation time','DOUBLE'), 0x012000007: ( 'timer activation number','LONG'), 0x013000000: ( 'markers','SUBBLOCK'), 0x014000000: ( 'marker','SUBBLOCK'), 0x014000001: ( 'marker name','ASCII'), 0x014000002: ( 'marker description','ASCII'), 0x014000003: ( 'marker trigger in','ASCII'), 0x014000004: ( 'marker trigger out','ASCII'), } pylibtiff-0.3.0~svn78/libtiff/tests/0000775000175100017510000000000011660704745016411 5ustar tilletillepylibtiff-0.3.0~svn78/libtiff/tests/test_lzw.py0000664000175100017510000000135711405511635020633 0ustar tilletille import numpy from tempfile import mktemp from libtiff import TIFFfile, TIFF from libtiff.tif_lzw import encode as c_encode, decode as c_decode #def TIFFencode(arr): # fn = mktemp('.tif') # tif = TIFF.open(fn, 'w+') # tif.write_image(arr.view(numpy.uint8), compression='lzw') # tif.close() # tif = TIFFfile(fn) # data, names = tif.get_samples(leave_compressed=True) # return data[0][0] def test_encode(): for arr in [ numpy.array([7,7,7,8,8,7,7,6,6], numpy.uint8), numpy.array(range(400000), numpy.uint8), numpy.array([1,3,7,15,31,63], numpy.uint8)]: rarr = c_encode(arr) arr2 = c_decode(rarr, arr.nbytes) assert arr2.nbytes == arr.nbytes and (arr2==arr).all(),`arr2,arr` pylibtiff-0.3.0~svn78/libtiff/tests/test_tiff_file.py0000664000175100017510000000215711656204757021761 0ustar tilletille import os import atexit from tempfile import mktemp from numpy import * from libtiff import TIFF from libtiff import TIFFfile, TIFFimage def test_write_read(): for compression in [None, 'lzw']: for itype in [uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64, complex64, complex128]: image = array([[1,2,3], [4,5,6]], itype) fn = mktemp('.tif') if 0: tif = TIFF.open(fn,'w') tif.write_image(image, compression=compression) tif.close() else: tif = TIFFimage(image) tif.write_file(fn, compression=compression) del tif tif = TIFFfile(fn) data, names = tif.get_samples() assert names==['sample0'],`names` assert len(data)==1, `len(data)` assert image.dtype==data[0].dtype, `image.dtype, data[0].dtype` assert (image==data[0]).all() #os.remove(fn) atexit.register(os.remove, fn) pylibtiff-0.3.0~svn78/libtiff/tests/test_tiff_array.py0000664000175100017510000000324711656204757022161 0ustar tilletille import os import atexit from tempfile import mktemp from numpy import * from libtiff import TIFF from libtiff import TIFFfile, TIFFimage def test_simple_slicing(): for planar_config in [1,2]: for compression in [None, 'lzw']: for itype in [uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64, complex64, complex128]: image = random.randint(0, 100, size=(10,6,7)).astype (itype) fn = mktemp('.tif') if 0: if planar_config==2: continue tif = TIFF.open(fn,'w') tif.write_image(image, compression=compression) tif.close() else: tif = TIFFimage(image) tif.write_file(fn, compression=compression, planar_config=planar_config) del tif tif = TIFFfile(fn) arr = tif.get_tiff_array() data = arr[:] assert len(data)==len (image), `len(data)` assert image.dtype==data.dtype, `image.dtype, data[0].dtype` assert (image==data).all() assert arr.shape==image.shape indices = [0, slice(None), slice (0,2), slice (0,5,2)] for i0 in indices[:1]: for i1 in indices: for i2 in indices: sl = (i0, i1, i2) assert (arr[sl]==image[sl]).all(),`sl` #os.remove(fn) atexit.register(os.remove, fn) pylibtiff-0.3.0~svn78/libtiff/tests/test_simple.py0000664000175100017510000000220211467615014021302 0ustar tilletille import os from tempfile import mktemp from numpy import * from libtiff import TIFF def test_write_read(): for itype in [uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64, complex64, complex128]: image = array([[1,2,3], [4,5,6]], itype) fn = mktemp('.tif') tif = TIFF.open(fn,'w') tif.write_image(image) tif.close() tif = TIFF.open(fn,'r') image2 = tif.read_image() tif.close() os.remove(fn) assert image.dtype==image2.dtype assert (image==image2).all() def test_slicing(): shape = (16, 16) image = random.randint(255, size=shape) for i in range(shape[0]): for j in range(shape[1]): image1 = image[:i+1,:j+1] fn = mktemp('.tif') tif = TIFF.open(fn,'w') tif.write_image(image1) tif.close() tif = TIFF.open(fn,'r') image2 = tif.read_image() tif.close() assert (image1==image2).all(),`i,j` os.remove(fn) pylibtiff-0.3.0~svn78/libtiff/tests/test_tiff_image.py0000664000175100017510000000477111656204757022130 0ustar tilletilleimport os import atexit from tempfile import mktemp from numpy import * from libtiff import TIFFfile, TIFFimage, TIFF def test_rw_rgb(): itype = uint8 dt = dtype(dict(names = list('rgb'), formats = [itype]*3)) image = zeros((2,3), dtype=dt) image['r'][:,0] = 250 image['g'][:,1] = 251 image['b'][:,2] = 252 fn = mktemp('.tif') tif = TIFFimage(image) tif.write_file(fn,compression='lzw')#, samples='rgb') del tif tif = TIFFfile(fn) data, names = tif.get_samples() #os.remove(fn) atexit.register(os.remove, fn) print image print data assert itype == data[0].dtype, `itype, data[0].dtype` assert (image['r']==data[0]).all() assert (image['g']==data[1]).all() assert (image['b']==data[2]).all() def test_write_read(): for compression in ['none', 'lzw']: for itype in [uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64, complex64, complex128]: image = array([[1,2,3], [4,5,6]], itype) fn = mktemp('.tif') tif = TIFFimage(image) tif.write_file(fn, compression=compression) del tif tif = TIFFfile(fn) data, names = tif.get_samples() #os.remove(fn) atexit.register(os.remove, fn) assert names==['sample0'],`names` assert len(data)==1, `len(data)` assert image.dtype==data[0].dtype, `image.dtype,data[0].dtype` assert (image==data[0]).all() def test_write_lzw(): for itype in [uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64, complex64, complex128]: #image = array([[1,2,3], [4,5,6]], itype) image = array([range(10000)], itype) #image = array([[0]*14000], itype) fn = mktemp('.tif') tif = TIFFimage(image) tif.write_file(fn, compression='lzw') del tif #os.system('wc %s; echo %s' % (fn, image.nbytes)) tif = TIFF.open(fn,'r') image2 = tif.read_image() tif.close() #os.remove(fn) atexit.register(os.remove, fn) for i in range(image.size): if image.flat[i] != image2.flat[i]: print `i, image.flat[i-5:i+5].view(dtype=uint8),image2.flat[i-5:i+5].view(dtype=uint8)` break assert image.dtype==image2.dtype assert (image==image2).all() pylibtiff-0.3.0~svn78/libtiff/tiff_base.py0000664000175100017510000000003311503605355017530 0ustar tilletille class TiffBase: pass pylibtiff-0.3.0~svn78/libtiff/script_options.py0000664000175100017510000001032011440524600020656 0ustar tilletille __all__ = ['set_formatter', 'set_info_options', 'set_convert_options'] import os from optparse import OptionGroup, NO_DEFAULT from optparse import TitledHelpFormatter class MyHelpFormatter(TitledHelpFormatter): def format_option(self, option): old_help = option.help default = option.default if isinstance (default, str) and ' ' in default: default = repr (default) if option.help is None: option.help = 'Specify a %s.' % (option.type) if option.type=='choice': choices = [] for choice in option.choices: if choice==option.default: if ' ' in choice: choice = repr(choice) choice = '['+choice+']' else: if ' ' in choice: choice = repr(choice) choices.append (choice) option.help = '%s Choices: %s.'% (option.help, ', '.join(choices)) else: if default != NO_DEFAULT: if option.action=='store_false': option.help = '%s Default: %s.'% (option.help, not default) else: option.help = '%s Default: %s.'% (option.help, default) result = TitledHelpFormatter.format_option (self, option) option.help = old_help return result help_formatter = MyHelpFormatter() def set_formatter(parser): """Set customized help formatter. """ parser.formatter = help_formatter def set_convert_options(parser): set_formatter(parser) if os.name == 'posix': try: import matplotlib matplotlib.use('GTkAgg') parser.run_methods = ['subcommand'] except ImportError: pass parser.set_usage ('%prog [options] -i INPUTPATH [-o OUTPUTPATH]') parser.set_description('Convert INPUTPATH to OUTPUTPATH.') parser.add_option ('--input-path', '-i', type = 'file', metavar='INPUTPATH', help = 'Specify INPUTPATH.' ) parser.add_option ('--output-path', '-o', type = 'file', metavar='OUTPUTPATH', help = 'Specify OUTPUTPATH.' ) parser.add_option ('--compression', type = 'choice', default='none', choices = ['none', 'lzw'], help = 'Specify compression.' ) parser.add_option ('--slice', type = 'string', help = 'Specify slice using form ":,:,:"' ) def set_info_options(parser): set_formatter(parser) if os.name == 'posix': try: import matplotlib matplotlib.use('GTkAgg') parser.run_methods = ['subcommand'] except ImportError: pass parser.set_usage ('%prog [options] -i INPUTPATH') parser.set_description('Show INPUTPATHs information.') parser.add_option ('--input-path', '-i', type = 'file', metavar='INPUTPATH', help = 'Specify INPUTPATH.' ) parser.add_option ('--memory-usage', action = 'store_true', default=False, help = 'Show TIFF file memory usage.' ) parser.add_option ('--no-memory-usage', dest='memory_usage', action = 'store_false', help = 'See --memory-usage.' ) parser.add_option ('--ifd', action = 'store_true', default=False, help = 'Show all TIFF file image file directory. By default, only the first IFD is shown.' ) parser.add_option ('--no-ifd', dest='ifd', action = 'store_false', help='See --ifd.') parser.add_option ('--human', action = 'store_true', default=False, help = 'Show human readable values' ) parser.add_option ('--no-human', dest='human', action = 'store_false', help='See --human.') pylibtiff-0.3.0~svn78/libtiff/test_bittools.py0000664000175100017510000000266011373247533020521 0ustar tilletille import numpy import bittools def tobinary(arr): return ''.join([str(bittools.getbit (arr,i)) for i in range (arr.nbytes*8)]) def test_setgetbit(): # bit-wise copy arr = numpy.array(range(256), dtype=numpy.float64) arr2 = numpy.zeros(arr.shape, dtype=arr.dtype) for i in range(arr.nbytes * 8): b = bittools.getbit(arr, i) bittools.setbit(arr2, i, b) assert (arr==arr2).all(),`arr,arr2` print 'ok' def test_setgetword(): for dtype in [numpy.ubyte, numpy.int32, numpy.float64]: arr = numpy.array(range(-256,256), dtype=dtype) arr2 = numpy.zeros(arr.shape, dtype=arr.dtype) for i in range (arr.nbytes): word, next = bittools.getword (arr,i*8,8) bittools.setword (arr2,i*8,8,word) assert (arr==arr2).all(),`arr,arr2` print 'ok' def test_wordbits (): for width in range (1,64+1): arr = numpy.array([131,17,235], dtype=numpy.int64) arr2 = numpy.zeros((1+width//8), dtype=arr.dtype) bstr = tobinary(arr) word, next = bittools.getword(arr, 0, width) if width > 7: assert word==arr[0],`word, arr[0], bstr` bittools.setword (arr2, 0, width, word) assert bittools.getword (arr2, 0, width)[0]==word assert tobinary(arr2)[:width] == bstr[:width],`tobinary(arr2)[:width], bstr[:width]` if __name__=='__main__': test_setgetbit() test_setgetword() test_wordbits () pylibtiff-0.3.0~svn78/libtiff/tiff_array.py0000664000175100017510000000654211515636236017754 0ustar tilletille""" Implements an array of TIFF sample images. """ # Author: Pearu Peterson # Created: Nov 2010 from __future__ import division import sys import numpy __all__ = ['TiffArray'] class TiffArray: """ Holds a sequence of homogeneous TiffPlane's. TiffPlane's are homogeneous if they contain sample images of same shape and type. Otherwise TiffPlane's may contain images from different TIFF files with different pixel content. """ def __init__ (self, planes): self.planes = [] self.shape = () self.dtype = None map(self.append, planes) def __len__(self): return self.shape[0] def __getitem__ (self, index): try: if isinstance(index, (int, long)): if self.sample_index is None: print self.shape return self.planes[index][()] elif isinstance (index, slice): indices = range (*index.indices(self.shape[0])) r = numpy.empty((len(indices),)+self.shape[1:], dtype=self.dtype) for i,j in enumerate(indices): r[i] = self.planes[j][()] return r elif isinstance(index, tuple): if len (index)==0: return self[:] if len (index)==1: return self[index[0]] index0 = index[0] if isinstance(index0, (int, long)): return self.planes[index0][index[1:]] elif isinstance (index0, slice): indices = range (*index0.indices(self.shape[0])) for i,j in enumerate(indices): s = self.planes[j][index[1:]] if i==0: r = numpy.empty((len(indices),)+s.shape, dtype=self.dtype) r[i] = s return r except IOError, msg: sys.stderr.write('%s.__getitem__:\n%s\n' % (self.__class__.__name__, msg)) sys.stderr.flush () return None raise NotImplementedError (`index`) def append(self, plane): """ Append tiff plane to tiff array. """ if self.planes: if not self.planes[0].check_same_shape_and_type (plane): raise TypeError('planes are not homogeneous (same shape and sample type), expected %s but got %s' % ((self.planes[0].shape, self.dtype), (plane.shape, plane.dtype))) self.shape = (self.shape[0]+1,) + self.shape[1:] else: self.dtype = plane.dtype self.shape = (1,) + plane.shape self.sample_index = plane.sample_index self.planes.append(plane) def extend(self, other): """ Extend tiff array with the content of another. """ map(self.append, other.planes) def get_voxel_sizes(self): """ Return ZYX voxel sizes in microns. """ return self.planes[0].ifd.get_voxel_sizes() def get_pixel_sizes(self): """ Return YX pixel sizes in microns. """ return self.planes[0].ifd.get_pixel_sizes() def get_time(self, index = 0): """ Return time parameter of a plane. """ return self.planes[index].time @property def nbytes(self): return self.shape[0] * self.shape[1] * self.shape[2] * self.dtype.itemsize pylibtiff-0.3.0~svn78/libtiff/tiff_h_3_9_5.py0000664000175100017510000002561311651465222017757 0ustar tilletilleTIFF_VERSION = 42 TIFF_BIGTIFF_VERSION = 43 TIFF_BIGENDIAN = 19789 TIFF_LITTLEENDIAN = 18761 MDI_LITTLEENDIAN = 20549 MDI_BIGENDIAN = 17744 TIFF_MAGIC_SIZE = 2 TIFF_VERSION_SIZE = 2 TIFF_DIROFFSET_SIZE = 4 TIFFTAG_SUBFILETYPE = 254 FILETYPE_REDUCEDIMAGE = 1 FILETYPE_PAGE = 2 FILETYPE_MASK = 4 TIFFTAG_OSUBFILETYPE = 255 OFILETYPE_IMAGE = 1 OFILETYPE_REDUCEDIMAGE = 2 OFILETYPE_PAGE = 3 TIFFTAG_IMAGEWIDTH = 256 TIFFTAG_IMAGELENGTH = 257 TIFFTAG_BITSPERSAMPLE = 258 TIFFTAG_COMPRESSION = 259 COMPRESSION_NONE = 1 COMPRESSION_CCITTRLE = 2 COMPRESSION_CCITTFAX3 = 3 COMPRESSION_CCITT_T4 = 3 COMPRESSION_CCITTFAX4 = 4 COMPRESSION_CCITT_T6 = 4 COMPRESSION_LZW = 5 COMPRESSION_OJPEG = 6 COMPRESSION_JPEG = 7 COMPRESSION_NEXT = 32766 COMPRESSION_CCITTRLEW = 32771 COMPRESSION_PACKBITS = 32773 COMPRESSION_THUNDERSCAN = 32809 COMPRESSION_IT8CTPAD = 32895 COMPRESSION_IT8LW = 32896 COMPRESSION_IT8MP = 32897 COMPRESSION_IT8BL = 32898 COMPRESSION_PIXARFILM = 32908 COMPRESSION_PIXARLOG = 32909 COMPRESSION_DEFLATE = 32946 COMPRESSION_ADOBE_DEFLATE = 8 COMPRESSION_DCS = 32947 COMPRESSION_JBIG = 34661 COMPRESSION_SGILOG = 34676 COMPRESSION_SGILOG24 = 34677 COMPRESSION_JP2000 = 34712 TIFFTAG_PHOTOMETRIC = 262 PHOTOMETRIC_MINISWHITE = 0 PHOTOMETRIC_MINISBLACK = 1 PHOTOMETRIC_RGB = 2 PHOTOMETRIC_PALETTE = 3 PHOTOMETRIC_MASK = 4 PHOTOMETRIC_SEPARATED = 5 PHOTOMETRIC_YCBCR = 6 PHOTOMETRIC_CIELAB = 8 PHOTOMETRIC_ICCLAB = 9 PHOTOMETRIC_ITULAB = 10 PHOTOMETRIC_LOGL = 32844 PHOTOMETRIC_LOGLUV = 32845 TIFFTAG_THRESHHOLDING = 263 THRESHHOLD_BILEVEL = 1 THRESHHOLD_HALFTONE = 2 THRESHHOLD_ERRORDIFFUSE = 3 TIFFTAG_CELLWIDTH = 264 TIFFTAG_CELLLENGTH = 265 TIFFTAG_FILLORDER = 266 FILLORDER_MSB2LSB = 1 FILLORDER_LSB2MSB = 2 TIFFTAG_DOCUMENTNAME = 269 TIFFTAG_IMAGEDESCRIPTION = 270 TIFFTAG_MAKE = 271 TIFFTAG_MODEL = 272 TIFFTAG_STRIPOFFSETS = 273 TIFFTAG_ORIENTATION = 274 ORIENTATION_TOPLEFT = 1 ORIENTATION_TOPRIGHT = 2 ORIENTATION_BOTRIGHT = 3 ORIENTATION_BOTLEFT = 4 ORIENTATION_LEFTTOP = 5 ORIENTATION_RIGHTTOP = 6 ORIENTATION_RIGHTBOT = 7 ORIENTATION_LEFTBOT = 8 TIFFTAG_SAMPLESPERPIXEL = 277 TIFFTAG_ROWSPERSTRIP = 278 TIFFTAG_STRIPBYTECOUNTS = 279 TIFFTAG_MINSAMPLEVALUE = 280 TIFFTAG_MAXSAMPLEVALUE = 281 TIFFTAG_XRESOLUTION = 282 TIFFTAG_YRESOLUTION = 283 TIFFTAG_PLANARCONFIG = 284 PLANARCONFIG_CONTIG = 1 PLANARCONFIG_SEPARATE = 2 TIFFTAG_PAGENAME = 285 TIFFTAG_XPOSITION = 286 TIFFTAG_YPOSITION = 287 TIFFTAG_FREEOFFSETS = 288 TIFFTAG_FREEBYTECOUNTS = 289 TIFFTAG_GRAYRESPONSEUNIT = 290 GRAYRESPONSEUNIT_10S = 1 GRAYRESPONSEUNIT_100S = 2 GRAYRESPONSEUNIT_1000S = 3 GRAYRESPONSEUNIT_10000S = 4 GRAYRESPONSEUNIT_100000S = 5 TIFFTAG_GRAYRESPONSECURVE = 291 TIFFTAG_GROUP3OPTIONS = 292 TIFFTAG_T4OPTIONS = 292 GROUP3OPT_2DENCODING = 1 GROUP3OPT_UNCOMPRESSED = 2 GROUP3OPT_FILLBITS = 4 TIFFTAG_GROUP4OPTIONS = 293 TIFFTAG_T6OPTIONS = 293 GROUP4OPT_UNCOMPRESSED = 2 TIFFTAG_RESOLUTIONUNIT = 296 RESUNIT_NONE = 1 RESUNIT_INCH = 2 RESUNIT_CENTIMETER = 3 TIFFTAG_PAGENUMBER = 297 TIFFTAG_COLORRESPONSEUNIT = 300 COLORRESPONSEUNIT_10S = 1 COLORRESPONSEUNIT_100S = 2 COLORRESPONSEUNIT_1000S = 3 COLORRESPONSEUNIT_10000S = 4 COLORRESPONSEUNIT_100000S = 5 TIFFTAG_TRANSFERFUNCTION = 301 TIFFTAG_SOFTWARE = 305 TIFFTAG_DATETIME = 306 TIFFTAG_ARTIST = 315 TIFFTAG_HOSTCOMPUTER = 316 TIFFTAG_PREDICTOR = 317 PREDICTOR_NONE = 1 PREDICTOR_HORIZONTAL = 2 PREDICTOR_FLOATINGPOINT = 3 TIFFTAG_WHITEPOINT = 318 TIFFTAG_PRIMARYCHROMATICITIES = 319 TIFFTAG_COLORMAP = 320 TIFFTAG_HALFTONEHINTS = 321 TIFFTAG_TILEWIDTH = 322 TIFFTAG_TILELENGTH = 323 TIFFTAG_TILEOFFSETS = 324 TIFFTAG_TILEBYTECOUNTS = 325 TIFFTAG_BADFAXLINES = 326 TIFFTAG_CLEANFAXDATA = 327 CLEANFAXDATA_CLEAN = 0 CLEANFAXDATA_REGENERATED = 1 CLEANFAXDATA_UNCLEAN = 2 TIFFTAG_CONSECUTIVEBADFAXLINES = 328 TIFFTAG_SUBIFD = 330 TIFFTAG_INKSET = 332 INKSET_CMYK = 1 INKSET_MULTIINK = 2 TIFFTAG_INKNAMES = 333 TIFFTAG_NUMBEROFINKS = 334 TIFFTAG_DOTRANGE = 336 TIFFTAG_TARGETPRINTER = 337 TIFFTAG_EXTRASAMPLES = 338 EXTRASAMPLE_UNSPECIFIED = 0 EXTRASAMPLE_ASSOCALPHA = 1 EXTRASAMPLE_UNASSALPHA = 2 TIFFTAG_SAMPLEFORMAT = 339 SAMPLEFORMAT_UINT = 1 SAMPLEFORMAT_INT = 2 SAMPLEFORMAT_IEEEFP = 3 SAMPLEFORMAT_VOID = 4 SAMPLEFORMAT_COMPLEXINT = 5 SAMPLEFORMAT_COMPLEXIEEEFP = 6 TIFFTAG_SMINSAMPLEVALUE = 340 TIFFTAG_SMAXSAMPLEVALUE = 341 TIFFTAG_CLIPPATH = 343 TIFFTAG_XCLIPPATHUNITS = 344 TIFFTAG_YCLIPPATHUNITS = 345 TIFFTAG_INDEXED = 346 TIFFTAG_JPEGTABLES = 347 TIFFTAG_OPIPROXY = 351 TIFFTAG_JPEGPROC = 512 JPEGPROC_BASELINE = 1 JPEGPROC_LOSSLESS = 14 TIFFTAG_JPEGIFOFFSET = 513 TIFFTAG_JPEGIFBYTECOUNT = 514 TIFFTAG_JPEGRESTARTINTERVAL = 515 TIFFTAG_JPEGLOSSLESSPREDICTORS = 517 TIFFTAG_JPEGPOINTTRANSFORM = 518 TIFFTAG_JPEGQTABLES = 519 TIFFTAG_JPEGDCTABLES = 520 TIFFTAG_JPEGACTABLES = 521 TIFFTAG_YCBCRCOEFFICIENTS = 529 TIFFTAG_YCBCRSUBSAMPLING = 530 TIFFTAG_YCBCRPOSITIONING = 531 YCBCRPOSITION_CENTERED = 1 YCBCRPOSITION_COSITED = 2 TIFFTAG_REFERENCEBLACKWHITE = 532 TIFFTAG_XMLPACKET = 700 TIFFTAG_OPIIMAGEID = 32781 TIFFTAG_REFPTS = 32953 TIFFTAG_REGIONTACKPOINT = 32954 TIFFTAG_REGIONWARPCORNERS = 32955 TIFFTAG_REGIONAFFINE = 32956 TIFFTAG_MATTEING = 32995 TIFFTAG_DATATYPE = 32996 TIFFTAG_IMAGEDEPTH = 32997 TIFFTAG_TILEDEPTH = 32998 TIFFTAG_PIXAR_IMAGEFULLWIDTH = 33300 TIFFTAG_PIXAR_IMAGEFULLLENGTH = 33301 TIFFTAG_PIXAR_TEXTUREFORMAT = 33302 TIFFTAG_PIXAR_WRAPMODES = 33303 TIFFTAG_PIXAR_FOVCOT = 33304 TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN = 33305 TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA = 33306 TIFFTAG_WRITERSERIALNUMBER = 33405 TIFFTAG_COPYRIGHT = 33432 TIFFTAG_RICHTIFFIPTC = 33723 TIFFTAG_IT8SITE = 34016 TIFFTAG_IT8COLORSEQUENCE = 34017 TIFFTAG_IT8HEADER = 34018 TIFFTAG_IT8RASTERPADDING = 34019 TIFFTAG_IT8BITSPERRUNLENGTH = 34020 TIFFTAG_IT8BITSPEREXTENDEDRUNLENGTH = 34021 TIFFTAG_IT8COLORTABLE = 34022 TIFFTAG_IT8IMAGECOLORINDICATOR = 34023 TIFFTAG_IT8BKGCOLORINDICATOR = 34024 TIFFTAG_IT8IMAGECOLORVALUE = 34025 TIFFTAG_IT8BKGCOLORVALUE = 34026 TIFFTAG_IT8PIXELINTENSITYRANGE = 34027 TIFFTAG_IT8TRANSPARENCYINDICATOR = 34028 TIFFTAG_IT8COLORCHARACTERIZATION = 34029 TIFFTAG_IT8HCUSAGE = 34030 TIFFTAG_IT8TRAPINDICATOR = 34031 TIFFTAG_IT8CMYKEQUIVALENT = 34032 TIFFTAG_FRAMECOUNT = 34232 TIFFTAG_PHOTOSHOP = 34377 TIFFTAG_EXIFIFD = 34665 TIFFTAG_ICCPROFILE = 34675 TIFFTAG_JBIGOPTIONS = 34750 TIFFTAG_GPSIFD = 34853 TIFFTAG_FAXRECVPARAMS = 34908 TIFFTAG_FAXSUBADDRESS = 34909 TIFFTAG_FAXRECVTIME = 34910 TIFFTAG_FAXDCS = 34911 TIFFTAG_STONITS = 37439 TIFFTAG_FEDEX_EDR = 34929 TIFFTAG_INTEROPERABILITYIFD = 40965 TIFFTAG_DNGVERSION = 50706 TIFFTAG_DNGBACKWARDVERSION = 50707 TIFFTAG_UNIQUECAMERAMODEL = 50708 TIFFTAG_LOCALIZEDCAMERAMODEL = 50709 TIFFTAG_CFAPLANECOLOR = 50710 TIFFTAG_CFALAYOUT = 50711 TIFFTAG_LINEARIZATIONTABLE = 50712 TIFFTAG_BLACKLEVELREPEATDIM = 50713 TIFFTAG_BLACKLEVEL = 50714 TIFFTAG_BLACKLEVELDELTAH = 50715 TIFFTAG_BLACKLEVELDELTAV = 50716 TIFFTAG_WHITELEVEL = 50717 TIFFTAG_DEFAULTSCALE = 50718 TIFFTAG_DEFAULTCROPORIGIN = 50719 TIFFTAG_DEFAULTCROPSIZE = 50720 TIFFTAG_COLORMATRIX1 = 50721 TIFFTAG_COLORMATRIX2 = 50722 TIFFTAG_CAMERACALIBRATION1 = 50723 TIFFTAG_CAMERACALIBRATION2 = 50724 TIFFTAG_REDUCTIONMATRIX1 = 50725 TIFFTAG_REDUCTIONMATRIX2 = 50726 TIFFTAG_ANALOGBALANCE = 50727 TIFFTAG_ASSHOTNEUTRAL = 50728 TIFFTAG_ASSHOTWHITEXY = 50729 TIFFTAG_BASELINEEXPOSURE = 50730 TIFFTAG_BASELINENOISE = 50731 TIFFTAG_BASELINESHARPNESS = 50732 TIFFTAG_BAYERGREENSPLIT = 50733 TIFFTAG_LINEARRESPONSELIMIT = 50734 TIFFTAG_CAMERASERIALNUMBER = 50735 TIFFTAG_LENSINFO = 50736 TIFFTAG_CHROMABLURRADIUS = 50737 TIFFTAG_ANTIALIASSTRENGTH = 50738 TIFFTAG_SHADOWSCALE = 50739 TIFFTAG_DNGPRIVATEDATA = 50740 TIFFTAG_MAKERNOTESAFETY = 50741 TIFFTAG_CALIBRATIONILLUMINANT1 = 50778 TIFFTAG_CALIBRATIONILLUMINANT2 = 50779 TIFFTAG_BESTQUALITYSCALE = 50780 TIFFTAG_RAWDATAUNIQUEID = 50781 TIFFTAG_ORIGINALRAWFILENAME = 50827 TIFFTAG_ORIGINALRAWFILEDATA = 50828 TIFFTAG_ACTIVEAREA = 50829 TIFFTAG_MASKEDAREAS = 50830 TIFFTAG_ASSHOTICCPROFILE = 50831 TIFFTAG_ASSHOTPREPROFILEMATRIX = 50832 TIFFTAG_CURRENTICCPROFILE = 50833 TIFFTAG_CURRENTPREPROFILEMATRIX = 50834 TIFFTAG_DCSHUESHIFTVALUES = 65535 TIFFTAG_FAXMODE = 65536 FAXMODE_CLASSIC = 0 FAXMODE_NORTC = 1 FAXMODE_NOEOL = 2 FAXMODE_BYTEALIGN = 4 FAXMODE_WORDALIGN = 8 FAXMODE_CLASSF = 1 TIFFTAG_JPEGQUALITY = 65537 TIFFTAG_JPEGCOLORMODE = 65538 JPEGCOLORMODE_RAW = 0 JPEGCOLORMODE_RGB = 1 TIFFTAG_JPEGTABLESMODE = 65539 JPEGTABLESMODE_QUANT = 1 JPEGTABLESMODE_HUFF = 2 TIFFTAG_FAXFILLFUNC = 65540 TIFFTAG_PIXARLOGDATAFMT = 65549 PIXARLOGDATAFMT_8BIT = 0 PIXARLOGDATAFMT_8BITABGR = 1 PIXARLOGDATAFMT_11BITLOG = 2 PIXARLOGDATAFMT_12BITPICIO = 3 PIXARLOGDATAFMT_16BIT = 4 PIXARLOGDATAFMT_FLOAT = 5 TIFFTAG_DCSIMAGERTYPE = 65550 DCSIMAGERMODEL_M3 = 0 DCSIMAGERMODEL_M5 = 1 DCSIMAGERMODEL_M6 = 2 DCSIMAGERFILTER_IR = 0 DCSIMAGERFILTER_MONO = 1 DCSIMAGERFILTER_CFA = 2 DCSIMAGERFILTER_OTHER = 3 TIFFTAG_DCSINTERPMODE = 65551 DCSINTERPMODE_NORMAL = 0 DCSINTERPMODE_PREVIEW = 1 TIFFTAG_DCSBALANCEARRAY = 65552 TIFFTAG_DCSCORRECTMATRIX = 65553 TIFFTAG_DCSGAMMA = 65554 TIFFTAG_DCSTOESHOULDERPTS = 65555 TIFFTAG_DCSCALIBRATIONFD = 65556 TIFFTAG_ZIPQUALITY = 65557 TIFFTAG_PIXARLOGQUALITY = 65558 TIFFTAG_DCSCLIPRECTANGLE = 65559 TIFFTAG_SGILOGDATAFMT = 65560 SGILOGDATAFMT_FLOAT = 0 SGILOGDATAFMT_16BIT = 1 SGILOGDATAFMT_RAW = 2 SGILOGDATAFMT_8BIT = 3 TIFFTAG_SGILOGENCODE = 65561 SGILOGENCODE_NODITHER = 0 SGILOGENCODE_RANDITHER = 1 EXIFTAG_EXPOSURETIME = 33434 EXIFTAG_FNUMBER = 33437 EXIFTAG_EXPOSUREPROGRAM = 34850 EXIFTAG_SPECTRALSENSITIVITY = 34852 EXIFTAG_ISOSPEEDRATINGS = 34855 EXIFTAG_OECF = 34856 EXIFTAG_EXIFVERSION = 36864 EXIFTAG_DATETIMEORIGINAL = 36867 EXIFTAG_DATETIMEDIGITIZED = 36868 EXIFTAG_COMPONENTSCONFIGURATION = 37121 EXIFTAG_COMPRESSEDBITSPERPIXEL = 37122 EXIFTAG_SHUTTERSPEEDVALUE = 37377 EXIFTAG_APERTUREVALUE = 37378 EXIFTAG_BRIGHTNESSVALUE = 37379 EXIFTAG_EXPOSUREBIASVALUE = 37380 EXIFTAG_MAXAPERTUREVALUE = 37381 EXIFTAG_SUBJECTDISTANCE = 37382 EXIFTAG_METERINGMODE = 37383 EXIFTAG_LIGHTSOURCE = 37384 EXIFTAG_FLASH = 37385 EXIFTAG_FOCALLENGTH = 37386 EXIFTAG_SUBJECTAREA = 37396 EXIFTAG_MAKERNOTE = 37500 EXIFTAG_USERCOMMENT = 37510 EXIFTAG_SUBSECTIME = 37520 EXIFTAG_SUBSECTIMEORIGINAL = 37521 EXIFTAG_SUBSECTIMEDIGITIZED = 37522 EXIFTAG_FLASHPIXVERSION = 40960 EXIFTAG_COLORSPACE = 40961 EXIFTAG_PIXELXDIMENSION = 40962 EXIFTAG_PIXELYDIMENSION = 40963 EXIFTAG_RELATEDSOUNDFILE = 40964 EXIFTAG_FLASHENERGY = 41483 EXIFTAG_SPATIALFREQUENCYRESPONSE = 41484 EXIFTAG_FOCALPLANEXRESOLUTION = 41486 EXIFTAG_FOCALPLANEYRESOLUTION = 41487 EXIFTAG_FOCALPLANERESOLUTIONUNIT = 41488 EXIFTAG_SUBJECTLOCATION = 41492 EXIFTAG_EXPOSUREINDEX = 41493 EXIFTAG_SENSINGMETHOD = 41495 EXIFTAG_FILESOURCE = 41728 EXIFTAG_SCENETYPE = 41729 EXIFTAG_CFAPATTERN = 41730 EXIFTAG_CUSTOMRENDERED = 41985 EXIFTAG_EXPOSUREMODE = 41986 EXIFTAG_WHITEBALANCE = 41987 EXIFTAG_DIGITALZOOMRATIO = 41988 EXIFTAG_FOCALLENGTHIN35MMFILM = 41989 EXIFTAG_SCENECAPTURETYPE = 41990 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_CONTRAST = 41992 EXIFTAG_SATURATION = 41993 EXIFTAG_SHARPNESS = 41994 EXIFTAG_DEVICESETTINGDESCRIPTION = 41995 EXIFTAG_SUBJECTDISTANCERANGE = 41996 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_IMAGEUNIQUEID = 42016 pylibtiff-0.3.0~svn78/libtiff/version.py0000664000175100017510000000174711370362345017311 0ustar tilletille # THIS FILE IS GENERATED FROM libtiff/setup.py short_version='0.3.0' version='0.3.0' release=False if not release: version += '.dev' import os svn_version_file = os.path.join(os.path.dirname(__file__), '__svn_version__.py') svn_entries_file = os.path.join(os.path.dirname(__file__),'.svn', 'entries') if os.path.isfile(svn_version_file): import imp svn = imp.load_module('libtiff.__svn_version__', open(svn_version_file), svn_version_file, ('.py','U',1)) version += svn.version elif os.path.isfile(svn_entries_file): import subprocess try: svn_version = subprocess.Popen(["svnversion", os.path.dirname (__file__)], stdout=subprocess.PIPE).communicate()[0] except: pass else: version += svn_version.strip() print version pylibtiff-0.3.0~svn78/libtiff/tiff_h_3_9_4.py0000664000175100017510000002561311467615075017766 0ustar tilletilleTIFF_VERSION = 42 TIFF_BIGTIFF_VERSION = 43 TIFF_BIGENDIAN = 19789 TIFF_LITTLEENDIAN = 18761 MDI_LITTLEENDIAN = 20549 MDI_BIGENDIAN = 17744 TIFF_MAGIC_SIZE = 2 TIFF_VERSION_SIZE = 2 TIFF_DIROFFSET_SIZE = 4 TIFFTAG_SUBFILETYPE = 254 FILETYPE_REDUCEDIMAGE = 1 FILETYPE_PAGE = 2 FILETYPE_MASK = 4 TIFFTAG_OSUBFILETYPE = 255 OFILETYPE_IMAGE = 1 OFILETYPE_REDUCEDIMAGE = 2 OFILETYPE_PAGE = 3 TIFFTAG_IMAGEWIDTH = 256 TIFFTAG_IMAGELENGTH = 257 TIFFTAG_BITSPERSAMPLE = 258 TIFFTAG_COMPRESSION = 259 COMPRESSION_NONE = 1 COMPRESSION_CCITTRLE = 2 COMPRESSION_CCITTFAX3 = 3 COMPRESSION_CCITT_T4 = 3 COMPRESSION_CCITTFAX4 = 4 COMPRESSION_CCITT_T6 = 4 COMPRESSION_LZW = 5 COMPRESSION_OJPEG = 6 COMPRESSION_JPEG = 7 COMPRESSION_NEXT = 32766 COMPRESSION_CCITTRLEW = 32771 COMPRESSION_PACKBITS = 32773 COMPRESSION_THUNDERSCAN = 32809 COMPRESSION_IT8CTPAD = 32895 COMPRESSION_IT8LW = 32896 COMPRESSION_IT8MP = 32897 COMPRESSION_IT8BL = 32898 COMPRESSION_PIXARFILM = 32908 COMPRESSION_PIXARLOG = 32909 COMPRESSION_DEFLATE = 32946 COMPRESSION_ADOBE_DEFLATE = 8 COMPRESSION_DCS = 32947 COMPRESSION_JBIG = 34661 COMPRESSION_SGILOG = 34676 COMPRESSION_SGILOG24 = 34677 COMPRESSION_JP2000 = 34712 TIFFTAG_PHOTOMETRIC = 262 PHOTOMETRIC_MINISWHITE = 0 PHOTOMETRIC_MINISBLACK = 1 PHOTOMETRIC_RGB = 2 PHOTOMETRIC_PALETTE = 3 PHOTOMETRIC_MASK = 4 PHOTOMETRIC_SEPARATED = 5 PHOTOMETRIC_YCBCR = 6 PHOTOMETRIC_CIELAB = 8 PHOTOMETRIC_ICCLAB = 9 PHOTOMETRIC_ITULAB = 10 PHOTOMETRIC_LOGL = 32844 PHOTOMETRIC_LOGLUV = 32845 TIFFTAG_THRESHHOLDING = 263 THRESHHOLD_BILEVEL = 1 THRESHHOLD_HALFTONE = 2 THRESHHOLD_ERRORDIFFUSE = 3 TIFFTAG_CELLWIDTH = 264 TIFFTAG_CELLLENGTH = 265 TIFFTAG_FILLORDER = 266 FILLORDER_MSB2LSB = 1 FILLORDER_LSB2MSB = 2 TIFFTAG_DOCUMENTNAME = 269 TIFFTAG_IMAGEDESCRIPTION = 270 TIFFTAG_MAKE = 271 TIFFTAG_MODEL = 272 TIFFTAG_STRIPOFFSETS = 273 TIFFTAG_ORIENTATION = 274 ORIENTATION_TOPLEFT = 1 ORIENTATION_TOPRIGHT = 2 ORIENTATION_BOTRIGHT = 3 ORIENTATION_BOTLEFT = 4 ORIENTATION_LEFTTOP = 5 ORIENTATION_RIGHTTOP = 6 ORIENTATION_RIGHTBOT = 7 ORIENTATION_LEFTBOT = 8 TIFFTAG_SAMPLESPERPIXEL = 277 TIFFTAG_ROWSPERSTRIP = 278 TIFFTAG_STRIPBYTECOUNTS = 279 TIFFTAG_MINSAMPLEVALUE = 280 TIFFTAG_MAXSAMPLEVALUE = 281 TIFFTAG_XRESOLUTION = 282 TIFFTAG_YRESOLUTION = 283 TIFFTAG_PLANARCONFIG = 284 PLANARCONFIG_CONTIG = 1 PLANARCONFIG_SEPARATE = 2 TIFFTAG_PAGENAME = 285 TIFFTAG_XPOSITION = 286 TIFFTAG_YPOSITION = 287 TIFFTAG_FREEOFFSETS = 288 TIFFTAG_FREEBYTECOUNTS = 289 TIFFTAG_GRAYRESPONSEUNIT = 290 GRAYRESPONSEUNIT_10S = 1 GRAYRESPONSEUNIT_100S = 2 GRAYRESPONSEUNIT_1000S = 3 GRAYRESPONSEUNIT_10000S = 4 GRAYRESPONSEUNIT_100000S = 5 TIFFTAG_GRAYRESPONSECURVE = 291 TIFFTAG_GROUP3OPTIONS = 292 TIFFTAG_T4OPTIONS = 292 GROUP3OPT_2DENCODING = 1 GROUP3OPT_UNCOMPRESSED = 2 GROUP3OPT_FILLBITS = 4 TIFFTAG_GROUP4OPTIONS = 293 TIFFTAG_T6OPTIONS = 293 GROUP4OPT_UNCOMPRESSED = 2 TIFFTAG_RESOLUTIONUNIT = 296 RESUNIT_NONE = 1 RESUNIT_INCH = 2 RESUNIT_CENTIMETER = 3 TIFFTAG_PAGENUMBER = 297 TIFFTAG_COLORRESPONSEUNIT = 300 COLORRESPONSEUNIT_10S = 1 COLORRESPONSEUNIT_100S = 2 COLORRESPONSEUNIT_1000S = 3 COLORRESPONSEUNIT_10000S = 4 COLORRESPONSEUNIT_100000S = 5 TIFFTAG_TRANSFERFUNCTION = 301 TIFFTAG_SOFTWARE = 305 TIFFTAG_DATETIME = 306 TIFFTAG_ARTIST = 315 TIFFTAG_HOSTCOMPUTER = 316 TIFFTAG_PREDICTOR = 317 PREDICTOR_NONE = 1 PREDICTOR_HORIZONTAL = 2 PREDICTOR_FLOATINGPOINT = 3 TIFFTAG_WHITEPOINT = 318 TIFFTAG_PRIMARYCHROMATICITIES = 319 TIFFTAG_COLORMAP = 320 TIFFTAG_HALFTONEHINTS = 321 TIFFTAG_TILEWIDTH = 322 TIFFTAG_TILELENGTH = 323 TIFFTAG_TILEOFFSETS = 324 TIFFTAG_TILEBYTECOUNTS = 325 TIFFTAG_BADFAXLINES = 326 TIFFTAG_CLEANFAXDATA = 327 CLEANFAXDATA_CLEAN = 0 CLEANFAXDATA_REGENERATED = 1 CLEANFAXDATA_UNCLEAN = 2 TIFFTAG_CONSECUTIVEBADFAXLINES = 328 TIFFTAG_SUBIFD = 330 TIFFTAG_INKSET = 332 INKSET_CMYK = 1 INKSET_MULTIINK = 2 TIFFTAG_INKNAMES = 333 TIFFTAG_NUMBEROFINKS = 334 TIFFTAG_DOTRANGE = 336 TIFFTAG_TARGETPRINTER = 337 TIFFTAG_EXTRASAMPLES = 338 EXTRASAMPLE_UNSPECIFIED = 0 EXTRASAMPLE_ASSOCALPHA = 1 EXTRASAMPLE_UNASSALPHA = 2 TIFFTAG_SAMPLEFORMAT = 339 SAMPLEFORMAT_UINT = 1 SAMPLEFORMAT_INT = 2 SAMPLEFORMAT_IEEEFP = 3 SAMPLEFORMAT_VOID = 4 SAMPLEFORMAT_COMPLEXINT = 5 SAMPLEFORMAT_COMPLEXIEEEFP = 6 TIFFTAG_SMINSAMPLEVALUE = 340 TIFFTAG_SMAXSAMPLEVALUE = 341 TIFFTAG_CLIPPATH = 343 TIFFTAG_XCLIPPATHUNITS = 344 TIFFTAG_YCLIPPATHUNITS = 345 TIFFTAG_INDEXED = 346 TIFFTAG_JPEGTABLES = 347 TIFFTAG_OPIPROXY = 351 TIFFTAG_JPEGPROC = 512 JPEGPROC_BASELINE = 1 JPEGPROC_LOSSLESS = 14 TIFFTAG_JPEGIFOFFSET = 513 TIFFTAG_JPEGIFBYTECOUNT = 514 TIFFTAG_JPEGRESTARTINTERVAL = 515 TIFFTAG_JPEGLOSSLESSPREDICTORS = 517 TIFFTAG_JPEGPOINTTRANSFORM = 518 TIFFTAG_JPEGQTABLES = 519 TIFFTAG_JPEGDCTABLES = 520 TIFFTAG_JPEGACTABLES = 521 TIFFTAG_YCBCRCOEFFICIENTS = 529 TIFFTAG_YCBCRSUBSAMPLING = 530 TIFFTAG_YCBCRPOSITIONING = 531 YCBCRPOSITION_CENTERED = 1 YCBCRPOSITION_COSITED = 2 TIFFTAG_REFERENCEBLACKWHITE = 532 TIFFTAG_XMLPACKET = 700 TIFFTAG_OPIIMAGEID = 32781 TIFFTAG_REFPTS = 32953 TIFFTAG_REGIONTACKPOINT = 32954 TIFFTAG_REGIONWARPCORNERS = 32955 TIFFTAG_REGIONAFFINE = 32956 TIFFTAG_MATTEING = 32995 TIFFTAG_DATATYPE = 32996 TIFFTAG_IMAGEDEPTH = 32997 TIFFTAG_TILEDEPTH = 32998 TIFFTAG_PIXAR_IMAGEFULLWIDTH = 33300 TIFFTAG_PIXAR_IMAGEFULLLENGTH = 33301 TIFFTAG_PIXAR_TEXTUREFORMAT = 33302 TIFFTAG_PIXAR_WRAPMODES = 33303 TIFFTAG_PIXAR_FOVCOT = 33304 TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN = 33305 TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA = 33306 TIFFTAG_WRITERSERIALNUMBER = 33405 TIFFTAG_COPYRIGHT = 33432 TIFFTAG_RICHTIFFIPTC = 33723 TIFFTAG_IT8SITE = 34016 TIFFTAG_IT8COLORSEQUENCE = 34017 TIFFTAG_IT8HEADER = 34018 TIFFTAG_IT8RASTERPADDING = 34019 TIFFTAG_IT8BITSPERRUNLENGTH = 34020 TIFFTAG_IT8BITSPEREXTENDEDRUNLENGTH = 34021 TIFFTAG_IT8COLORTABLE = 34022 TIFFTAG_IT8IMAGECOLORINDICATOR = 34023 TIFFTAG_IT8BKGCOLORINDICATOR = 34024 TIFFTAG_IT8IMAGECOLORVALUE = 34025 TIFFTAG_IT8BKGCOLORVALUE = 34026 TIFFTAG_IT8PIXELINTENSITYRANGE = 34027 TIFFTAG_IT8TRANSPARENCYINDICATOR = 34028 TIFFTAG_IT8COLORCHARACTERIZATION = 34029 TIFFTAG_IT8HCUSAGE = 34030 TIFFTAG_IT8TRAPINDICATOR = 34031 TIFFTAG_IT8CMYKEQUIVALENT = 34032 TIFFTAG_FRAMECOUNT = 34232 TIFFTAG_PHOTOSHOP = 34377 TIFFTAG_EXIFIFD = 34665 TIFFTAG_ICCPROFILE = 34675 TIFFTAG_JBIGOPTIONS = 34750 TIFFTAG_GPSIFD = 34853 TIFFTAG_FAXRECVPARAMS = 34908 TIFFTAG_FAXSUBADDRESS = 34909 TIFFTAG_FAXRECVTIME = 34910 TIFFTAG_FAXDCS = 34911 TIFFTAG_STONITS = 37439 TIFFTAG_FEDEX_EDR = 34929 TIFFTAG_INTEROPERABILITYIFD = 40965 TIFFTAG_DNGVERSION = 50706 TIFFTAG_DNGBACKWARDVERSION = 50707 TIFFTAG_UNIQUECAMERAMODEL = 50708 TIFFTAG_LOCALIZEDCAMERAMODEL = 50709 TIFFTAG_CFAPLANECOLOR = 50710 TIFFTAG_CFALAYOUT = 50711 TIFFTAG_LINEARIZATIONTABLE = 50712 TIFFTAG_BLACKLEVELREPEATDIM = 50713 TIFFTAG_BLACKLEVEL = 50714 TIFFTAG_BLACKLEVELDELTAH = 50715 TIFFTAG_BLACKLEVELDELTAV = 50716 TIFFTAG_WHITELEVEL = 50717 TIFFTAG_DEFAULTSCALE = 50718 TIFFTAG_DEFAULTCROPORIGIN = 50719 TIFFTAG_DEFAULTCROPSIZE = 50720 TIFFTAG_COLORMATRIX1 = 50721 TIFFTAG_COLORMATRIX2 = 50722 TIFFTAG_CAMERACALIBRATION1 = 50723 TIFFTAG_CAMERACALIBRATION2 = 50724 TIFFTAG_REDUCTIONMATRIX1 = 50725 TIFFTAG_REDUCTIONMATRIX2 = 50726 TIFFTAG_ANALOGBALANCE = 50727 TIFFTAG_ASSHOTNEUTRAL = 50728 TIFFTAG_ASSHOTWHITEXY = 50729 TIFFTAG_BASELINEEXPOSURE = 50730 TIFFTAG_BASELINENOISE = 50731 TIFFTAG_BASELINESHARPNESS = 50732 TIFFTAG_BAYERGREENSPLIT = 50733 TIFFTAG_LINEARRESPONSELIMIT = 50734 TIFFTAG_CAMERASERIALNUMBER = 50735 TIFFTAG_LENSINFO = 50736 TIFFTAG_CHROMABLURRADIUS = 50737 TIFFTAG_ANTIALIASSTRENGTH = 50738 TIFFTAG_SHADOWSCALE = 50739 TIFFTAG_DNGPRIVATEDATA = 50740 TIFFTAG_MAKERNOTESAFETY = 50741 TIFFTAG_CALIBRATIONILLUMINANT1 = 50778 TIFFTAG_CALIBRATIONILLUMINANT2 = 50779 TIFFTAG_BESTQUALITYSCALE = 50780 TIFFTAG_RAWDATAUNIQUEID = 50781 TIFFTAG_ORIGINALRAWFILENAME = 50827 TIFFTAG_ORIGINALRAWFILEDATA = 50828 TIFFTAG_ACTIVEAREA = 50829 TIFFTAG_MASKEDAREAS = 50830 TIFFTAG_ASSHOTICCPROFILE = 50831 TIFFTAG_ASSHOTPREPROFILEMATRIX = 50832 TIFFTAG_CURRENTICCPROFILE = 50833 TIFFTAG_CURRENTPREPROFILEMATRIX = 50834 TIFFTAG_DCSHUESHIFTVALUES = 65535 TIFFTAG_FAXMODE = 65536 FAXMODE_CLASSIC = 0 FAXMODE_NORTC = 1 FAXMODE_NOEOL = 2 FAXMODE_BYTEALIGN = 4 FAXMODE_WORDALIGN = 8 FAXMODE_CLASSF = 1 TIFFTAG_JPEGQUALITY = 65537 TIFFTAG_JPEGCOLORMODE = 65538 JPEGCOLORMODE_RAW = 0 JPEGCOLORMODE_RGB = 1 TIFFTAG_JPEGTABLESMODE = 65539 JPEGTABLESMODE_QUANT = 1 JPEGTABLESMODE_HUFF = 2 TIFFTAG_FAXFILLFUNC = 65540 TIFFTAG_PIXARLOGDATAFMT = 65549 PIXARLOGDATAFMT_8BIT = 0 PIXARLOGDATAFMT_8BITABGR = 1 PIXARLOGDATAFMT_11BITLOG = 2 PIXARLOGDATAFMT_12BITPICIO = 3 PIXARLOGDATAFMT_16BIT = 4 PIXARLOGDATAFMT_FLOAT = 5 TIFFTAG_DCSIMAGERTYPE = 65550 DCSIMAGERMODEL_M3 = 0 DCSIMAGERMODEL_M5 = 1 DCSIMAGERMODEL_M6 = 2 DCSIMAGERFILTER_IR = 0 DCSIMAGERFILTER_MONO = 1 DCSIMAGERFILTER_CFA = 2 DCSIMAGERFILTER_OTHER = 3 TIFFTAG_DCSINTERPMODE = 65551 DCSINTERPMODE_NORMAL = 0 DCSINTERPMODE_PREVIEW = 1 TIFFTAG_DCSBALANCEARRAY = 65552 TIFFTAG_DCSCORRECTMATRIX = 65553 TIFFTAG_DCSGAMMA = 65554 TIFFTAG_DCSTOESHOULDERPTS = 65555 TIFFTAG_DCSCALIBRATIONFD = 65556 TIFFTAG_ZIPQUALITY = 65557 TIFFTAG_PIXARLOGQUALITY = 65558 TIFFTAG_DCSCLIPRECTANGLE = 65559 TIFFTAG_SGILOGDATAFMT = 65560 SGILOGDATAFMT_FLOAT = 0 SGILOGDATAFMT_16BIT = 1 SGILOGDATAFMT_RAW = 2 SGILOGDATAFMT_8BIT = 3 TIFFTAG_SGILOGENCODE = 65561 SGILOGENCODE_NODITHER = 0 SGILOGENCODE_RANDITHER = 1 EXIFTAG_EXPOSURETIME = 33434 EXIFTAG_FNUMBER = 33437 EXIFTAG_EXPOSUREPROGRAM = 34850 EXIFTAG_SPECTRALSENSITIVITY = 34852 EXIFTAG_ISOSPEEDRATINGS = 34855 EXIFTAG_OECF = 34856 EXIFTAG_EXIFVERSION = 36864 EXIFTAG_DATETIMEORIGINAL = 36867 EXIFTAG_DATETIMEDIGITIZED = 36868 EXIFTAG_COMPONENTSCONFIGURATION = 37121 EXIFTAG_COMPRESSEDBITSPERPIXEL = 37122 EXIFTAG_SHUTTERSPEEDVALUE = 37377 EXIFTAG_APERTUREVALUE = 37378 EXIFTAG_BRIGHTNESSVALUE = 37379 EXIFTAG_EXPOSUREBIASVALUE = 37380 EXIFTAG_MAXAPERTUREVALUE = 37381 EXIFTAG_SUBJECTDISTANCE = 37382 EXIFTAG_METERINGMODE = 37383 EXIFTAG_LIGHTSOURCE = 37384 EXIFTAG_FLASH = 37385 EXIFTAG_FOCALLENGTH = 37386 EXIFTAG_SUBJECTAREA = 37396 EXIFTAG_MAKERNOTE = 37500 EXIFTAG_USERCOMMENT = 37510 EXIFTAG_SUBSECTIME = 37520 EXIFTAG_SUBSECTIMEORIGINAL = 37521 EXIFTAG_SUBSECTIMEDIGITIZED = 37522 EXIFTAG_FLASHPIXVERSION = 40960 EXIFTAG_COLORSPACE = 40961 EXIFTAG_PIXELXDIMENSION = 40962 EXIFTAG_PIXELYDIMENSION = 40963 EXIFTAG_RELATEDSOUNDFILE = 40964 EXIFTAG_FLASHENERGY = 41483 EXIFTAG_SPATIALFREQUENCYRESPONSE = 41484 EXIFTAG_FOCALPLANEXRESOLUTION = 41486 EXIFTAG_FOCALPLANEYRESOLUTION = 41487 EXIFTAG_FOCALPLANERESOLUTIONUNIT = 41488 EXIFTAG_SUBJECTLOCATION = 41492 EXIFTAG_EXPOSUREINDEX = 41493 EXIFTAG_SENSINGMETHOD = 41495 EXIFTAG_FILESOURCE = 41728 EXIFTAG_SCENETYPE = 41729 EXIFTAG_CFAPATTERN = 41730 EXIFTAG_CUSTOMRENDERED = 41985 EXIFTAG_EXPOSUREMODE = 41986 EXIFTAG_WHITEBALANCE = 41987 EXIFTAG_DIGITALZOOMRATIO = 41988 EXIFTAG_FOCALLENGTHIN35MMFILM = 41989 EXIFTAG_SCENECAPTURETYPE = 41990 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_CONTRAST = 41992 EXIFTAG_SATURATION = 41993 EXIFTAG_SHARPNESS = 41994 EXIFTAG_DEVICESETTINGDESCRIPTION = 41995 EXIFTAG_SUBJECTDISTANCERANGE = 41996 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_GAINCONTROL = 41991 EXIFTAG_IMAGEUNIQUEID = 42016 pylibtiff-0.3.0~svn78/libtiff/tiff.py0000664000175100017510000000226111471264322016542 0ustar tilletille""" tiff - implements a numpy.memmap based TIFF file reader and writer allowing manipulating TIFF files that have sizes larger than available memory in computer. Usage: >>> tiff = TIFFfile('') >>> samples, sample_names = tiff.get_samples() >>> arr = tiff.get_tiff_array(sample_index=0, subfile_type=0) >>> tiff = TIFFimage(data, description=) >>> tiff.write_file (, compression='none'|'lzw') >>> del tiff # flush data to disk """ # Author: Pearu Peterson # Created: April 2010 from __future__ import division __all__ = ['TIFFfile', 'TIFFimage', 'TiffArray'] import os import sys import time import numpy from .tiff_file import TIFFfile from .tiff_image import TIFFimage from .tiff_array import TiffArray def main (): filename = sys.argv[1] if not os.path.isfile(filename): raise ValueError('File %r does not exists' % (filename)) t = TIFFfile(filename) t.show_memory_usage() e = t.IFD[0].entries[-1] assert e.is_lsm import lsm print lsm.lsmblock(e) print lsm.lsminfo(e, 0) #print lsm.filestructure(e) #print lsm.timestamps(e) #print lsm.channelwavelength(e) if __name__ == '__main__': main() pylibtiff-0.3.0~svn78/libtiff/lzw.py0000664000175100017510000001764311467615014016443 0ustar tilletille""" Encoder and decoder of Lempel-Ziv-Welch algorithm for TIFF. This module is obsolete, use tif_lzw extension module instead. """ # Author: Pearu Peterson # Created: May 2010 from __future__ import division import numpy default_backend='bittools' #default_backend='bittools' if default_backend=='bitarray': from bitarray import bitarray if default_backend=='bittools': from bittools import setword, getword CODECLEAR = 256 CODEEOI = 257 CODESTART = 258 def encode_bitarray(seq, max_bits=12): """ Compress sequence using Lempel-Ziv-Welch algorithm for TIFF. Parameters ---------- seq : {str, numpy.ndarray} max_bits : int Specify maximum bits for encoding table. Returns ------- bseq : bitarray See also -------- decode_bitarray """ if isinstance (seq, numpy.ndarray): seq = seq.tostring() r = bitarray(0, endian='little') write = r.fromword init_table = [(chr(code),code) for code in range (256)] table = {} table_get = table.get table_clear = table.clear table_update = table.update sup_code2 = (1<1: print 'Use --ifd to see the rest of %s IFD entries' % (len (tiff.IFD)-1) print 'data is contiguous:', tiff.is_contiguous () if tiff.check_memory_usage(verbose=False): print 'memory usage is ok' else: print 'memory usage has inconsistencies:' print '-----' tiff.check_memory_usage(verbose=True) print '-----' for subfile_type in tiff.get_subfile_types(): ifd0 = tiff.get_first_ifd (subfile_type=subfile_type) for sample_index, n in enumerate (ifd0.get_sample_names()): print 'Sample %s in subfile %s:' % (sample_index, subfile_type) arr = tiff.get_tiff_array (sample_index=sample_index, subfile_type=subfile_type) print ' shape=',arr.shape print ' dtype=',arr.dtype print ' pixel_sizes=',arr.get_pixel_sizes() def main (): try: from libtiff.optparse_gui import OptionParser except ImportError: from optparse import OptionParser raise from libtiff.script_options import set_info_options from libtiff.utils import Options parser = OptionParser() set_info_options (parser) if hasattr(parser, 'runner'): parser.runner = runner options, args = parser.parse_args() runner(parser, Options(options), args) return if __name__ == '__main__': main() pylibtiff-0.3.0~svn78/libtiff/scripts/convert.py0000664000175100017510000000745411374565712021003 0ustar tilletille#!/usr/bin/env python # -*- python -*- # Author: Pearu Peterson # Created: May 2010 from __future__ import division import os ### START UPDATE SYS.PATH ### ### END UPDATE SYS.PATH ### import numpy description_template = ''' DimensionX: %(DimensionX)s DimensionY: %(DimensionY)s DimensionZ: %(DimensionZ)s VoxelSizeX: %(VoxelSizeX)s VoxelSizeY: %(VoxelSizeY)s VoxelSizeZ: %(VoxelSizeZ)s NofStacks: 1 RotationAngle: %(RotationAngle)s PixelTime: %(PixelTime)s ENTRY_OBJECTIVE: %(Objective)s Objective: %(Objective)s ExcitationWavelength: %(ExcitationWavelength)s MicroscopeType: %(MicroscopeType)s ChannelName: %(ChannelName)s OriginalFile: %(OriginalFile)s ''' def runner (parser, options, args): if not hasattr(parser, 'runner'): options.output_path = None assert not args,`args` if options.input_path is None: parser.error('Expected --input-path but got nothing') input_path = options.input_path output_path = options.output_path assert output_path is None,`output_path` if output_path is None: b, e = os.path.splitext (input_path) b = os.path.basename (b) output_path = b + '_%(channel_name)s_%(slice)s.tif' from libtiff import TIFF from libtiff.tiff import TIFFfile, TIFFimage tiff = TIFFfile (input_path) samples, sample_names = tiff.get_samples() description = [] for ifd in tiff.IFD: assert ifd.get ('Compression').value==1,`ifd.get ('Compression')` s = ifd.get('ImageDescription') if s is not None: description.append(s.value.tostring()) init_description = '\n'.join (description) samples_list, names_list = tiff.get_samples() while samples_list: samples = samples_list.pop() if options.slice is not None: exec 'samples = samples[%s]' % (options.slice) name = names_list.pop() if tiff.is_lsm: dimensions = [tiff.lsmentry['Dimension'+x][0] for x in 'XYZ'] # px voxel_sizes = [tiff.lsmentry['VoxelSize'+x][0] for x in 'XYZ'] # m pixel_time = tiff.lsminfo.get('track pixel time')[0] # us, integration is >=70% of the pixel time rotation = tiff.lsminfo.get('recording rotation')[0] # deg objective = tiff.lsminfo.get('recording objective')[0] # objective description excitation_wavelength = tiff.lsminfo.get ('illumination channel wavelength')[0] # nm description = description_template % (dict( DimensionX=samples.shape[2], DimensionY=samples.shape[1], DimensionZ=samples.shape[0], VoxelSizeX=voxel_sizes[0], VoxelSizeY=voxel_sizes[1], VoxelSizeZ=voxel_sizes[2], RotationAngle=rotation, PixelTime = pixel_time, Objective = objective, MicroscopeType = 'confocal', OriginalFile = os.path.abspath(input_path), ExcitationWavelength = excitation_wavelength, ChannelName = name, )) + init_description description += '\n'+tiff.lsminfo.tostr (short=True) else: description = init_description tif = TIFFimage(samples, description=description) fn = output_path % dict(channel_name=name, slice=options.slice) tif.write_file(fn, compression=getattr(options,'compression', 'none')) return def main (): from libtiff.optparse_gui import OptionParser from libtiff.script_options import set_convert_options parser = OptionParser() set_convert_options (parser) if hasattr(parser, 'runner'): parser.runner = runner options, args = parser.parse_args() runner(parser, options, args) return if __name__ == '__main__': main() pylibtiff-0.3.0~svn78/libtiff/tiff_image.py0000664000175100017510000003710711625020022017677 0ustar tilletille""" Provides TIFFimage class. """ # Author: Pearu Peterson # Created: June 2010 from __future__ import division import os import sys import time import numpy import lzw import tif_lzw from .utils import bytes2str, VERBOSE from .tiff_data import tag_name2value, tag_value2type, tag_value2name, name2type, type2bytes, type2dtype VERBOSE=True class TIFFentry: """ Hold a IFD entry used by TIFFimage. """ def __init__ (self, tag): if isinstance(tag, str): tag = tag_name2value[tag] assert isinstance (tag, int), `tag` self.tag = tag self.type_name = tag_value2type[tag] self.type = name2type[self.type_name] self.type_nbytes = type2bytes[self.type] self.type_dtype = type2dtype[self.type] self.tag_name = tag_value2name.get(self.tag,'TAG%s' % (hex(self.tag),)) self.record = numpy.zeros((12,), dtype=numpy.ubyte) self.record[:2].view(dtype=numpy.uint16)[0] = self.tag self.record[2:4].view(dtype=numpy.uint16)[0] = self.type self.values = [] def __str__(self): return '%s(entry=(%s,%s,%s,%s))' % (self.__class__.__name__, self.tag_name, self.type_name, self.count, self.offset) __repr__ = __str__ @property def count(self): return self.record[4:8].view(dtype=numpy.uint32) @property def offset(self): return self.record[8:12].view(dtype=numpy.uint32) @property def nbytes(self): if self.offset_is_value: return 0 return self.count[0] * self.type_nbytes @property def offset_is_value (self): return not self.values and self.count[0]==1 and self.type_nbytes<=4 and self.type_name!='ASCII' def __getitem__ (self, index): if self.offset_is_value: if index>0: raise IndexError(`index`) return self.offset[0] return self.values[index] def add_value(self, value): if isinstance(value, (list, tuple)): map(self.add_value, value) elif self.type_name=='ASCII': value = str(value) if self.count[0]==0: self.values.append(value) else: self.values[0] += value self.count[0] = len(self.values[0]) + 1 elif self.type_nbytes<=4: self.count[0] += 1 if self.count[0]==1: self.offset[0] = value elif self.count[0]==2: self.values.append(self.offset[0]) self.values.append(value) self.offset[0] = 0 else: self.values.append(value) else: self.count[0] += 1 self.values.append(value) def set_value (self, value): assert self.type_name!='ASCII',`self` if self.count[0]: self.count[0] -= 1 if self.values: del self.values[-1] self.add_value (value) def set_offset(self, offset): self.offset[0] = offset def toarray(self, target = None): if self.offset_is_value: return if target is None: target = numpy.zeros((self.nbytes,), dtype=numpy.ubyte) dtype = target.dtype offset = 0 if self.type_name=='ASCII': data = numpy.array([self.values[0] + '\0']).view(dtype=numpy.ubyte) target[offset:offset+self.nbytes] = data else: for value in self.values: dtype = self.type_dtype if self.type_name=='RATIONAL' and isinstance(value, (int, long, float)): dtype = numpy.float64 target[offset:offset + self.type_nbytes].view(dtype=dtype)[0] = value offset += self.type_nbytes return target class TIFFimage: """ Hold an image stack that can be written to TIFF file. """ def __init__(self, data, description=''): """ data : {list, numpy.ndarray} Specify image data as a list of images or as an array with rank<=3. """ dtype = None if isinstance(data, list): image = data[0] self.length, self.width = image.shape self.depth = len(data) dtype = image.dtype elif isinstance(data, numpy.ndarray): shape = data.shape dtype = data.dtype if len (shape)==1: self.width, = shape self.length = 1 self.depth = 1 data = [[data]] elif len (shape)==2: self.length, self.width = shape self.depth = 1 data = [data] elif len (shape)==3: self.depth, self.length, self.width = shape else: raise NotImplementedError (`shape`) else: raise NotImplementedError (`type (data)`) self.data = data self.dtype = dtype self.description = description def write_file(self, filename, compression='none', strip_size = 2**13, planar_config = 1, validate = False, verbose=None): """ Write image data to TIFF file. Parameters ---------- filename : str compression : {'none', 'lzw'} strip_size : int Specify the size of uncompressed strip. validate : bool When True then check compression by decompression. verbose : {bool, None} When True then write progress information to stdout. When None then verbose is assumed for data that has size over 1MB. Returns ------- compression : float Compression factor. """ if verbose is None: nbytes = self.depth*self.length*self.width*self.dtype.itemsize verbose = nbytes >= 1024**2 if os.path.splitext (filename)[1].lower () not in ['.tif', '.tiff']: filename = filename + '.tif' if verbose: sys.stdout.write('Writing TIFF records to %s\n' % (filename)) sys.stdout.flush() compression_map = dict(packbits=32773, none=1, lzw=5, jpeg=6, ccitt1d=2, group3fax = 3, group4fax = 4 ) compress_map = dict(none=lambda data: data, lzw = tif_lzw.encode) decompress_map = dict(none=lambda data, bytes: data, lzw = tif_lzw.decode) compress = compress_map.get(compression or 'none', None) if compress is None: raise NotImplementedError (`compression`) decompress = decompress_map.get(compression or 'none', None) # compute tif file size and create image file directories data image_directories = [] total_size = 8 data_size = 0 image_data_size = 0 for i,image in enumerate(self.data): if verbose: sys.stdout.write('\r creating records: %5s%% done ' % (int(100.0*i/len(self.data)))) sys.stdout.flush () if image.dtype.kind=='V' and len(image.dtype.names)==3: # RGB image sample_format = dict(u=1,i=2,f=3,c=6).get(image.dtype.fields[image.dtype.names[0]][0].kind) bits_per_sample = [image.dtype.fields[f][0].itemsize*8 for f in image.dtype.names] samples_per_pixel = 3 photometric_interpretation = 2 else: # gray scale image sample_format = dict(u=1,i=2,f=3,c=6).get(image.dtype.kind) bits_per_sample = image.dtype.itemsize * 8 samples_per_pixel = 1 photometric_interpretation = 1 if sample_format is None: print 'Warning(TIFFimage.write_file): unknown data kind %r, mapping to void' % (image.dtype.kind) sample_format = 4 length, width = image.shape bytes_per_row = width * image.dtype.itemsize rows_per_strip = min(length, int(numpy.ceil(strip_size / bytes_per_row))) strips_per_image = int(numpy.floor((length + rows_per_strip - 1) / rows_per_strip)) assert bytes_per_row * rows_per_strip * strips_per_image >= image.nbytes d = dict(ImageWidth=width, ImageLength=length, Compression=compression_map.get(compression, 1), PhotometricInterpretation=photometric_interpretation, PlanarConfiguration=planar_config, Orientation=1, ResolutionUnit = 1, XResolution = 1, YResolution = 1, SamplesPerPixel = samples_per_pixel, RowsPerStrip = rows_per_strip, BitsPerSample = bits_per_sample, SampleFormat = sample_format, ) if i==0: d.update(dict( ImageDescription = self.description, Software = 'http://code.google.com/p/pylibtiff/')) entries = [] for tagname, value in d.items (): entry = TIFFentry(tagname) entry.add_value(value) entries.append(entry) total_size += 12 + entry.nbytes data_size += entry.nbytes strip_byte_counts = TIFFentry('StripByteCounts') strip_offsets = TIFFentry('StripOffsets') entries.append(strip_byte_counts) entries.append(strip_offsets) # strip_offsets and strip_byte_counts will be filled in the next loop if strips_per_image==1: assert strip_byte_counts.type_nbytes <= 4 assert strip_offsets.type_nbytes <= 4 total_size += 2*12 else: total_size += 2*12 + strips_per_image*(strip_byte_counts.type_nbytes + strip_offsets.type_nbytes) data_size += strips_per_image * (strip_byte_counts.type_nbytes + strip_offsets.type_nbytes) # image data: total_size += image.nbytes data_size += image.nbytes image_data_size += image.nbytes # records for nof IFD entries and offset to the next IFD: total_size += 2 + 4 # entries must be sorted by tag number entries.sort(cmp=lambda x,y: cmp(x.tag, y.tag)) strip_info = strip_offsets, strip_byte_counts, strips_per_image, rows_per_strip, bytes_per_row image_directories.append((entries, strip_info, image)) tif = numpy.memmap(filename, dtype=numpy.ubyte, mode='w+', shape=(total_size,)) def tif_write(tif, offset, data, tifs=[]): end = offset + data.nbytes if end > tif.size: size_incr = int((end - tif.size)/1024**2 + 1)*1024**2 new_size = tif.size + size_incr assert end <= new_size, `end, tif.size, size_incr, new_size` #sys.stdout.write('resizing: %s -> %s\n' % (tif.size, new_size)) #tif.resize(end, refcheck=False) tif._mmap.resize(new_size) new_tif = numpy.ndarray.__new__(numpy.memmap, (tif._mmap.size(), ), dtype = tif.dtype, buffer=tif._mmap) new_tif._parent = tif new_tif.__array_finalize__(tif) tif = new_tif tif[offset:end] = data return tif # write TIFF header tif[:2].view(dtype=numpy.uint16)[0] = 0x4949 # low-endian tif[2:4].view (dtype=numpy.uint16)[0] = 42 # magic number tif[4:8].view (dtype=numpy.uint32)[0] = 8 # offset to the first IFD offset = 8 data_offset = total_size - data_size image_data_offset = total_size - image_data_size first_data_offset = data_offset first_image_data_offset = image_data_offset start_time = time.time () compressed_data_size = 0 for i, (entries, strip_info, image) in enumerate(image_directories): strip_offsets, strip_byte_counts, strips_per_image, rows_per_strip, bytes_per_row = strip_info # write the nof IFD entries tif[offset:offset+2].view(dtype=numpy.uint16)[0] = len(entries) offset += 2 assert offset <= first_data_offset,`offset, first_data_offset` # write image data data = image.view(dtype=numpy.ubyte).reshape((image.nbytes,)) for j in range(strips_per_image): c = rows_per_strip * bytes_per_row k = j * c c -= max((j+1) * c - image.nbytes, 0) assert c>0,`c` orig_strip = data[k:k+c] strip = compress(orig_strip) if validate: test_strip = decompress(strip, orig_strip.nbytes) if (orig_strip!=test_strip).any(): raise RuntimeError('Compressed data is corrupted: cannot recover original data') compressed_data_size += strip.nbytes #print strip.size, strip.nbytes, strip.shape, tif[image_data_offset:image_data_offset+strip.nbytes].shape strip_offsets.add_value(image_data_offset) strip_byte_counts.add_value(strip.nbytes) tif = tif_write(tif, image_data_offset, strip) image_data_offset += strip.nbytes if j==0: first = strip_offsets[0] last = strip_offsets[-1] + strip_byte_counts[-1] # write IFD entries for entry in entries: data_size = entry.nbytes if data_size: entry.set_offset(data_offset) assert data_offset+data_size <= total_size, `data_offset+data_size,total_size` r = entry.toarray(tif[data_offset:data_offset + data_size]) assert r.nbytes==data_size data_offset += data_size assert data_offset <= first_image_data_offset,`data_offset, first_image_data_offset, i` tif[offset:offset+12] = entry.record offset += 12 assert offset <= first_data_offset,`offset, first_data_offset, i` # write offset to the next IFD tif[offset:offset+4].view(dtype=numpy.uint32)[0] = offset + 4 offset += 4 assert offset <= first_data_offset,`offset, first_data_offset` if verbose: sys.stdout.write('\r filling records: %5s%% done (%s/s)%s' \ % (int(100.0*(i+1)/len(image_directories)), bytes2str(int((image_data_offset-first_image_data_offset)/(time.time ()-start_time))), ' '*2)) if (i+1)==len (image_directories): sys.stdout.write ('\n') sys.stdout.flush () # last offset must be 0 tif[offset-4:offset].view(dtype=numpy.uint32)[0] = 0 compression = 1/(compressed_data_size/image_data_size) if compressed_data_size != image_data_size: sdiff = image_data_size - compressed_data_size total_size -= sdiff tif._mmap.resize(total_size) if verbose: sys.stdout.write(' resized records: %s -> %s (compression: %.2fx)\n' \ % (bytes2str(total_size + sdiff), bytes2str(total_size), compression)) sys.stdout.flush () del tif # flushing return compression pylibtiff-0.3.0~svn78/libtiff/tiff_channels_and_files.py0000664000175100017510000000411511515636236022427 0ustar tilletille from .tiff_base import TiffBase class TiffChannelsAndFiles (TiffBase): """ Represent a collection of TIFF files as a single TIFF source object. See also -------- TiffFile, TiffFiles """ def __init__(self, channels_files_map): """ Parameters ---------- channels_files_map : dict A dictionary of channel names and TIFF files (``TiffFiles`` instances) """ self.channels_files_map = channels_files_map def get_tiff_array (self, channel, sample_index=0, subfile_type=0, assume_one_image_per_file=False): """ Return an array of images for given channel. Parameters ---------- channel : str The name of a channel. sample_index : int Specify sample within a pixel. subfile_type : int Specify TIFF NewSubfileType used for collecting sample images. assume_one_image_per_file : bool When True then it is assumed that each TIFF file contains exactly one image and all images have the same parameters. This knowledge speeds up tiff_array construction as only the first TIFF file is opened for reading image parameters. The other TIFF files are opened only when particular images are accessed. Returns ------- tiff_array : TiffArray Array of sample images. The array has rank equal to 3. """ return self.channels_files_map[channel].get_tiff_array(sample_index=sample_index, subfile_type=subfile_type, assume_one_image_per_file=assume_one_image_per_file) def get_info(self): l = [] for channel, tiff in self.channels_files_map.items (): l.append ('Channel %s:' % (channel)) l.append ('-'*len(l[-1])) l.append (tiff.get_info()) return '\n'.join(l) def close(self): for channel, tiff in self.channels_files_map.items(): tiff.close() pylibtiff-0.3.0~svn78/libtiff/setup.py0000664000175100017510000000567511405511635016765 0ustar tilletille import sys from os.path import join, basename, dirname, splitext from glob import glob from numpy.distutils import log from distutils.dep_util import newer def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration package_name = 'libtiff' config = Configuration(package_name,parent_package,top_path) bitarray_path = 'bitarray-0.3.5-numpy/bitarray' # Add subpackages here: config.add_subpackage('bitarray', bitarray_path) # eof add. # Add extensions here: config.add_extension('bitarray._bitarray', join(bitarray_path,'_bitarray.c')) config.add_extension('bittools', join('src','bittools.c')) config.add_extension('tif_lzw', join('src','tif_lzw.c')) # eof add. config.make_svn_version_py() wininst = 'bdist_wininst' in sys.argv # Scripts support: files in scripts directories are considered as # python scripts that will be installed as # . to scripts installation directory. scripts = glob(join(config.local_path, 'scripts', '*.py')) scripts += glob(join(config.local_path, '*', 'scripts', '*.py')) for script in scripts: if basename (script).startswith (package_name): config.add_scripts(script) continue def generate_a_script(build_dir, script=script, config=config): dist = config.get_distribution() install_lib = dist.get_command_obj('install_lib') if not install_lib.finalized: install_lib.finalize_options() script_replace_text = '' install_lib = install_lib.install_dir if install_lib is not None: script_replace_text = ''' import sys if %(d)r not in sys.path: sys.path.insert(0, %(d)r) ''' % dict(d=install_lib) start_mark = '### START UPDATE SYS.PATH ###' end_mark = '### END UPDATE SYS.PATH ###' name = basename(script) if name.startswith (package_name): target_name = name elif wininst: target_name = package_name + '_' + name else: target_name = package_name + '.' + splitext(name)[0] target = join(build_dir, target_name) if newer(script, target) or 1: log.info('Creating %r', target) f = open (script, 'r') text = f.read() f.close() i = text.find(start_mark) if i != -1: j = text.find (end_mark) if j == -1: log.warn ("%r missing %r line", script, start_mark) new_text = text[:i+len (start_mark)] + script_replace_text + text[j:] else: new_text = text f = open(target, 'w') f.write(new_text) f.close() config.add_scripts(generate_a_script) return config pylibtiff-0.3.0~svn78/libtiff/optparse_gui.py0000664000175100017510000012111011440524600020300 0ustar tilletille'''A drop-in replacement for :pythonlib:`optparse` ("import iocbio.optparse_gui as optparse") Provides an identical interface to :pythonlib:`optparse`.OptionParser, in addition, it displays an automatically generated `wx `_ dialog in order to enter the options/args, instead of parsing command line arguments. This code is based on `optparse_gui module `_. Unfortunately the owner of optparse_gui did not respond to a request to join the optparse_gui group. By now this module has become more complete with more features. Module content -------------- ''' #Author: Pearu Peterson #Created: September 2009 __all__ = ['OptionParser', 'Option'] import os import signal import sys import re import shutil import tempfile import optparse import wx import subprocess as std_subprocess if os.name=='nt': from . import killableprocess as subprocess else: subprocess = std_subprocess multiprocessing = None try: import multiprocessing # Python <=2.5 users should install http://code.google.com/p/python-multiprocessing/ except ImportError: pass import traceback import Queue as queue from .utils import splitcommandline #try: # import matplotlib #except ImportError: # matplotlib = None #if matplotlib is not None: # matplotlib.use('Agg') # to avoid crashes with other backends __version__ = 0.9 debug = 1 bug_report_email = 'iocbio-bugs@googlegroups.com' smtp_server = 'cens.ioc.ee' bug_report_email = None # disables the Bug Report button signal_map = {} for n,v in signal.__dict__.items (): if isinstance(v, int): signal_map[v] = n def pretty_signal (s): r = signal_map.get(s) if r is None: r = signal_map.get(abs(s)) if r is None: return str(s) return '%s[%s]' % (s,r) def fix_float_string(s): if not s: return '0' if s[-1] in 'eE+-': return s + '0' return s def fix_int_string (s): if s in ['+','-']: return s + '0' return s def get_fixed_option_value (option, s): if option.type=='float': return fix_float_string(s) if option.type=='int': return fix_int_string(s) if option.type=='long': return fix_int_string(s) if option.type=='choice': choices = map(str, option.choices) try: return option.choices[choices.index(str(s))] except ValueError: pass return s def os_kill(pid, s): if os.name=='nt': if s==signal.SIGTERM or s==signal.SIGINT: import win32api handle = win32api.OpenProcess(1, 0, pid) return (0 != win32api.TerminateProcess(handle, 127)) if s==signal.SIGINT: import ctypes return (0 != ctypes.windll.kernel32.GenerateConsoleCtrlEvent (1, pid)) return os.kill (pid, s) class SysOutListener: debug_stream = '__stdout__' def __init__ (self, queue): self.queue = queue def write(self, string): if debug: stream = getattr (sys, self.debug_stream) if multiprocessing is not None or not string.startswith('\r'): stream.write(string) stream.flush() if multiprocessing is None: self.queue.put(string) else: if not self.queue._closed: self.queue.put(string) #wx.WakeUpIdle() # it does not seem to have effect, so using wx.Timer below def flush (self): if debug: stream = getattr (sys, self.debug_stream) stream.flush() class SysErrListener (SysOutListener): debug_stream = '__stderr__' def write (self, string): if not self.queue._closed: self.queue.put('@STDERR START@') SysOutListener.write (self, string) if not self.queue._closed: self.queue.put('@STDERR END@') class FunctionWrapper (object): def __init__ (self, func, log_queue = None): self.log_queue = log_queue self.func = func def __call__(self, *args, **kw): if self.log_queue is not None: saved_streams = sys.stdout, sys.stderr sys.stdout = SysOutListener(self.log_queue) sys.stderr = SysErrListener(self.log_queue) status = 0 try: self.func(*args, **kw) except: print "Exception in runner process:" print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60 status = 1 if self.log_queue is not None: sys.stdout, sys.stderr = saved_streams return status class OptionValidator (wx.PyValidator): def __init__ (self, option): wx.PyValidator.__init__ (self) self.option = option self.Bind (wx.EVT_CHAR, self.OnChar) def Clone (self): return OptionValidator(self.option) def Validate (self, win): return True def OnChar(self, event): key = event.GetKeyCode() if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: event.Skip () return if self.option.type == 'choice': return textCtrl = self.GetWindow() i = textCtrl.GetInsertionPoint() char = chr(key) text = textCtrl.GetValue() new_text = get_fixed_option_value(self.option, text[:i] + char + text[i:]) try: self.option.TYPE_CHECKER[self.option.type](self.option, self.option.dest, new_text) except optparse.OptionValueError, msg: if not wx.Validator_IsSilent(): wx.Bell() print >> sys.stderr, msg return event.Skip() class OptionPanel( wx.Panel ): def __init__(self, parent, option_list, main_frame): wx.Panel.__init__ (self, parent) sizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5) sizer.AddGrowableCol(1) destinations_list = [] for option in option_list: help = option.help or 'specify %s option. Default: %%default.' % (option.get_opt_string()) if '%default' in help: if option.default == optparse.NO_DEFAULT: help = help.replace ('%default', 'none') else: if option.action == 'store_false': help = help.replace ('%default', str(not option.default if option.default is not None else option.default)) else: help = help.replace ('%default', str(option.default)) if option.action == 'store': label_txt = option.get_opt_string() + '=' label = wx.StaticText(self, -1, label_txt ) label.SetHelpText( help) sizer.Add (label, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) if option.type == 'choice': if option.default == optparse.NO_DEFAULT: option.default = option.choices[0] ctrl = wx.ComboBox( self, -1, choices = map(str,option.choices), value = str(option.default), style = wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT ) sizer.Add (ctrl, 0, wx.EXPAND) sizer.Add ((20,20),0) elif option.type in ['string', 'int', 'float']: ctrl = wx.TextCtrl( self, -1, "", style=wx.TE_PROCESS_ENTER) if option.default not in [optparse.NO_DEFAULT, None]: ctrl.Value = str(option.default) sizer.Add (ctrl, 0, wx.EXPAND) sizer.Add ((20,20),0) elif option.type == 'multiline': ctrl = wx.TextCtrl( self, -1, "", size=(300,100), style = wx.TE_MULTILINE|wx.TE_PROCESS_ENTER ) if option.default not in [optparse.NO_DEFAULT, None]: ctrl.Value = option.default sizer.Add (ctrl, 0, wx.EXPAND) sizer.Add ((20,20),0) elif option.type in ['file', 'directory']: ctrl = wx.TextCtrl( self, -1, "") if option.default not in [optparse.NO_DEFAULT, None]: ctrl.Value = option.default sizer.Add (ctrl, 0, wx.EXPAND) browse = wx.Button( self, label='Browse..' ) browse.SetHelpText( 'Click to open %s browser' % (option.type) ) wx.EVT_BUTTON(self, browse.GetId(), main_frame.OnSelectPath) main_frame.browse_option_map[browse.GetId()] = option, ctrl sizer.Add(browse, 0, wx.ALIGN_CENTRE|wx.ALL, 1 ) else: raise NotImplementedError (`option.type`) destinations_list.append(option.dest) elif option.action in ['store_true', 'store_false']: if option.dest in destinations_list: continue ctrl = wx.CheckBox( self, -1, option.get_opt_string()) #ctrl = wx.ToggleButton( self, -1, option.get_opt_string()) if option.default not in [None, optparse.NO_DEFAULT]: if option.action=='store_false': ctrl.SetValue(not option.default) else: ctrl.SetValue(option.default) sizer.Add (ctrl, 0, wx.EXPAND) #sizer.Add ((20,20),0) sizer.Add (wx.StaticText(self,-1,help),0,wx.ALIGN_CENTER_VERTICAL) sizer.Add ((20,20),0) destinations_list.append(option.dest) elif option.action == 'help': ctrl = wx.Button( self, -1, 'Help') sizer.Add (ctrl, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) #sizer.Add ((20,20),0) sizer.Add (wx.StaticText(self,-1,"print help message"),0,wx.ALIGN_CENTER_VERTICAL) sizer.Add ((20,20),0) self.Bind(wx.EVT_BUTTON, main_frame.OnHelp, id=ctrl.GetId()) elif option.action == 'store_const': if option.dest in destinations_list: continue else: raise NotImplementedError (`option.action`) if option.type in option.TYPE_CHECKER: ctrl.SetValidator(OptionValidator(option)) ctrl.SetHelpText( help ) main_frame.option_controls[ option ] = ctrl self.SetSizer(sizer) self.Fit() #sizer.SetSizeHints(self) class OptparseFrame (wx.Frame): def capture_std_streams(self): global multiprocessing if multiprocessing is None: self.log_queue = queue.Queue() else: try: self.log_queue = multiprocessing.Queue() except WindowsError, msg: print 'multiprocessing.Queue raised WindowsError: %s' % (msg) print 'Disableing multiprocessing' multiprocessing = None self.log_queue = None return self.log_queue = queue.Queue() self._saved_streams = sys.stdout, sys.stderr sys.stdout = SysOutListener(self.log_queue) sys.stderr = SysErrListener(self.log_queue) def restore_std_streams (self): if self.log_queue is not None: sys.stdout, sys.stderr = self._saved_streams if multiprocessing is not None: self.log_queue.close() self.log_queue = None def __init__(self, option_parser): self.option_parser = option_parser self.option_parser.result = None self.capture_std_streams() run_methods = getattr(option_parser, 'run_methods', ['subprocess', 'subcommand']) self.option_controls = {} self.browse_option_map = {} self.process_list = [] wx.Frame.__init__(self, None, title="Optparse Dialog: %s" % (os.path.basename(sys.argv[0]))) p = wx.Panel(self) provider = wx.SimpleHelpProvider() wx.HelpProvider_Set(provider) nb = wx.Notebook(p) option_panel = OptionPanel(nb, option_parser.option_list, self) option_panel.SetHelpText (option_parser.description or 'Main options') nb.AddPage(option_panel, 'Main Options') pages = [] for group in option_parser.option_groups: if group in pages: continue option_panel = OptionPanel(nb, group.option_list, self) option_panel.SetHelpText (group.description or 'Group options') nb.AddPage(option_panel, group.title) pages.append(group) sizer_a = wx.BoxSizer (wx.VERTICAL) self.args_ctrl = args_ctrl = wx.TextCtrl(p, -1, '', size = ( -1, 80 ), style=wx.TE_MULTILINE | wx.TE_PROCESS_ENTER ) args_ctrl.SetHelpText ('''\ Arguments can be either separated by a space or a newline. Arguments that contain spaces must be entered like so: "arg with space"\ ''') label = wx.StaticText(p, -1, 'Arguments:' ) label.SetHelpText( 'Enter arguments here' ) sizer_a.Add (label, 0, wx.EXPAND) sizer_a.Add (args_ctrl, 0, wx.EXPAND) args_ctrl.Fit () sizer_b = wx.BoxSizer (wx.HORIZONTAL) cancel_b = wx.Button(p, -1, 'Cancel') cancel_b.SetHelpText('Cancel the program without saving') if debug>1: test_b = wx.Button(p, -1, 'Test') test_b.SetHelpText('Test options') run_b = None if option_parser.runner is not None or 1: self.run_b = run_b = wx.Button(p, -1, 'Run') run_b.SetHelpText('Run script with specified options and arguments.') batch_b = None if 0: self.batch_b = batch_b = wx.Button(p, -1, 'Batch') batch_b.SetHelpText('Run script with specified options and arguments in batch mode and exit.') self.exit_b = exit_b = wx.Button(p, -1, 'Exit') exit_b.SetHelpText('Exit without running the script. Any running process will be terminated.') send_b = None if bug_report_email: send_b = wx.Button (p, -1, 'Send Bug Report') send_b.SetHelpText ('Send bug report to %r. The bug report will include some environment data, used options and arguments, the content of the log window. If you want to add some notes then enter them to log window before pressing the Send Bug Report button.' % (bug_report_email)) runner_mth = None if multiprocessing is None or option_parser.runner is None: self.run_method = 'subcommand' else: self.run_method = run_methods[0] if len (run_methods)>1: runner_mth = wx.ComboBox( p, -1, choices = run_methods, value = run_methods[0], style = wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT ) runner_mth.SetHelpText ('Specify how to run application. Selecting subprocess means using multiprocessing.Process. Selecting subcommand means running the application with --no-gui option and using specified options. If application uses wx then one should select subcommand.') sizer_b.Add(cancel_b, 0, wx.ALL, 2) if debug>1: sizer_b.Add(test_b, 0, wx.ALL, 2) if run_b is not None: sizer_b.Add(run_b, 0, wx.ALL, 2) if runner_mth is not None: sizer_b.Add(runner_mth, 0, wx.ALL, 2) if batch_b is not None: sizer_b.Add(batch_b, 0, wx.ALL, 2) sizer_b.Add(exit_b, 0, wx.ALL, 2) if send_b is not None: sizer_b.Add(send_b, 0, wx.ALL, 2) self.log_window = log_window = wx.TextCtrl (p, -1, '', style = wx.TE_MULTILINE, size = ( -1, 120 )) log_window.SetFont(wx.Font(8, wx.MODERN, wx.NORMAL, wx.NORMAL, False)) log_window.SetHelpText ('Shows the standard output and error messages of a running process.') if wx.Platform != "__WXMSW__" or 1: help_b = wx.ContextHelpButton(p) sizer_b.Add((20,20),1) sizer_b.Add(help_b, 0, wx.RIGHT, 2) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(nb, 0, wx.EXPAND) sizer.Add(sizer_a, 0, wx.EXPAND, 5 ) sizer.Add(sizer_b, 0, wx.EXPAND|wx.BOTTOM, 5) sizer.Add(log_window, 1, wx.EXPAND) p.SetSizer(sizer) p.Fit () sizer.SetSizeHints(p) self.Fit () self.timer = wx.Timer(self) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_BUTTON, self.OnCancel, id=cancel_b.GetId()) if run_b is not None: self.Bind(wx.EVT_BUTTON, self.OnRun, id=run_b.GetId()) if runner_mth is not None: self.Bind(wx.EVT_COMBOBOX, self.OnSelectRunnerMethod, id=runner_mth.GetId()) if batch_b is not None: self.Bind(wx.EVT_BUTTON, self.OnBatch, id=batch_b.GetId()) if debug>1: self.Bind(wx.EVT_BUTTON, self.OnTest, id=test_b.GetId()) self.Bind(wx.EVT_BUTTON, self.OnExit, id=exit_b.GetId()) if send_b is not None: self.Bind(wx.EVT_BUTTON, self.OnSend, id=send_b.GetId()) self.Bind(wx.EVT_IDLE, self.OnUpdateLogWindow) self.Bind(wx.EVT_TIMER, self.OnUpdateLogWindow, self.timer) self.previous_position = 0 self._running_count = 0 def OnSend(self, event): msg = '' msg += '-'*40 + '\n' msg += 'Environment\n' msg += '='*40 + '\n' msg += 'os.getcwd(): %r\n' % (os.getcwd()) msg += 'sys.argv: ' + `sys.argv` + '\n' msg += 'sys.version: ' + `sys.version` + '\n' msg += 'sys.prefix: ' + `sys.prefix` + '\n' user = None for k in ['USER', 'LOGNAME', 'HOME', 'PYTHONPATH', 'PYTHONSTARTUP', 'LD_LIBRARY_PATH', 'PATH', 'LTSP_CLIENT','SSH_CONNECTION']: v = os.environ.get (k, None) if v is not None: msg += '%s: %r\n' % (k,v) if user is None and k in ['USER', 'LOGNAME']: user = v msg += 'Installation path: %r\n' % (os.path.dirname (__file__)) try: from . import version msg += 'Version: %s\n' % (version.version) except Exception, msg: msg += '%s\n' % (msg) pass msg += '-'*40 + '\n' msg += '\n' msg += '-'*40 + '\n' msg += 'Options\n' msg += '='*40 + '\n' try: values, args = self.option_parser.parse_options_args self.set_result() values, args = self.option_parser.get_result (values) msg += 'args=%r\n' % (args) for option in self.option_parser._get_all_options(): if option.dest: value = getattr(values, option.dest, None) if value is not None: msg += '%s[dest=%s]: %r\n' % (option.get_opt_string(), option.dest, value) except Exception, m: msg += 'Failed to get option results: %s\n' % (m) msg += '-'*40 + '\n' msg += '\n' msg += '-'*40 + '\n' msg += 'Content of log window\n' msg += '='*40 + '\n' msg += self.log_window.GetValue() + '\n' msg += '-'*40 + '\n' message = msg user_email = user + "@" + smtp_server import smtplib from email.MIMEText import MIMEText msg = MIMEText(msg) msg['Subject'] = '[IOCBio bug report] %s' % (sys.argv[0]) msg['From'] = user_email msg['To'] = bug_report_email try: s = smtplib.SMTP() s.connect(smtp_server) # Send the email - real from, real to, extra headers and content ... s.sendmail(user_email, bug_report_email, msg.as_string()) s.close() print 'Bug report succesfully sent to %r' % (bug_report_email) except Exception, msg: print 'Failed to send bug report: %s' % (msg) f = open('iocbio_bug_report.txt', 'w') f.write (message) f.close() print 'Please find the file "iocbio_bug_report.txt" in the current working directory and send it to %r using your favorite E-mail program.' % (bug_report_email) def OnSelectRunnerMethod(self, event): self.run_method = event.GetString() def OnUpdateLogWindow(self, event): if self.log_queue is not None and not self.log_queue.empty(): log_window = self.log_window is_stderr_message = None while 1: try: v = self.log_queue.get_nowait() except queue.Empty: break if v=='@STDERR START@': is_stderr_message = True elif v=='@STDERR END@': is_stderr_message = False else: # todo: use is_stderr_message to switch styles for line in v.splitlines(True): if line.startswith('\r'): log_window.Remove(self.previous_position, log_window.GetLastPosition()) line = line[1:] self.previous_position = log_window.GetInsertionPoint() log_window.AppendText(line) self.log_window.Refresh() if self.process_list: for index, (process, method) in enumerate(self.process_list): if method=='subprocess': if not process.is_alive(): self._cleanup_process(process, method) del self.process_list[index] elif method=='subcommand': if process.poll() is not None: self._cleanup_process(process, method) del self.process_list[index] else: raise NotImplementedError (`method`) self.cleanup_runner() def OnHelp (self, event): self.option_parser.print_help() def OnTest (self, event): values, args = self.option_parser.parse_options_args self.set_result() new_values, new_args = self.option_parser.get_result (values) print new_values, new_args def OnBatch (self, event): self.interrupt_runner() self.set_result() self.restore_std_streams() self.Close(True) def OnCancel (self, event): while self.process_list: self.interrupt_runner() self.result = None self.restore_std_streams() self.Close(True) sys.exit(0) def _start_process (self, method, show_info=[True]): self.set_result() values, args = self.option_parser.parse_options_args new_options, new_args = self.option_parser.get_result (values) if method=='subprocess': process = multiprocessing.Process(target=FunctionWrapper(self.option_parser.runner, self.log_queue), args=(self.option_parser, new_options, new_args)) process.start () return process elif method=='subcommand': if multiprocessing is None: print 'Using multiprocessing package is disabled.' if sys.version[:3]<='2.5': print 'Python 2.4, 2.5 users should install multiprocessing package from http://code.google.com/p/python-multiprocessing/' if show_info[0]: print 'Live session output is visible only in terminal.' print 'Wait for the runner process to finish..' show_info[0] = False self.option_parser.save_options(new_options, new_args) cmd_lst = [] cmd_prefix = getattr(new_options, 'runner_subcommand', sys.executable) if cmd_prefix: cmd_lst.append(cmd_prefix) cmd_lst.append (sys.argv[0]) cmd_lst.append ('--no-gui') cmd = ' '.join(cmd_lst) print 'Executing command:', cmd process = subprocess.Popen (cmd, shell=True, #stdout=std_subprocess.PIPE, stderr=std_subprocess.STDOUT) return process else: raise NotImplementedError (`method`) def _cleanup_process (self, process, method): if process is None: return if method=='subprocess': if process.exitcode is None: pid = process.pid print 'Runner %s (PID=%s) still running, trying to terminate' % (method, pid) process.terminate() process.join() print 'Runner %s has finished with exitcode=%s' % (method, pretty_signal(process.exitcode)) elif method=='subcommand': s = process.wait() if os.name=='nt': print 'Runner %s has finished with returncode=%s' % (method, pretty_signal (s)) else: pid = process.pid print 'Runner %s (PID=%s) has finished with returncode=%s' % (method, pid, pretty_signal(s)) else: raise NotImplementedError (`method`) def _interrupt_process (self, process, method): if method=='subprocess': if process.is_alive(): pid = process.pid os_kill(pid, signal.SIGINT) print print 'SIGINT signal has been sent to runner %s (PID=%s)' % (method, pid) elif method=='subcommand': if process.poll () is None: if os.name=='nt': process.kill(True, s=signal.SIGINT) print print 'SIGINT signal has been sent to runner %s' % (method) else: pid = process.pid os_kill(pid, signal.SIGINT) print print 'SIGINT signal has been sent to runner %s (PID=%s)' % (method, pid) else: raise NotImplementedError (`method`) def _terminate_process (self, process, method): if method=='subprocess': if prosess.is_alive(): print print 'Terminating runner %s' % (method) process.terminate() elif method=='subcommand': if process.poll() is None: if sys.version[:3]>='2.6': print print 'Terminating runner %s' % (method) process.terminate () else: if os.name=='nt': process.kill (True, s = signal.SIGTERM) else: os_kill (process.pid, signal.SIGTERM) print print 'SIGTERM signal has been sent to runner %s' % (method) else: raise NotImplementedError (`method`) def start_runner (self): if not self.process_list: self.exit_b.SetLabel('Stop') self.timer.Start(100) self.option_parser.run_method = self.run_method process = self._start_process(self.run_method) pid = process.pid print print 'Runner %s (PID=%s) has been started' % (self.run_method, pid) self.process_list.append((process, self.run_method)) def cleanup_runner (self): if not self.process_list: self.timer.Stop() self.exit_b.SetLabel('Exit') def interrupt_runner (self): if self.process_list: process, run_method = self.process_list[-1] del self.process_list[-1] self._interrupt_process(process, run_method) self._cleanup_process(process, run_method) self.cleanup_runner() def terminate_runner(self): if self.process_list: process, run_method = self.process_list[-1] del self.process_list[-1] self._terminate_process(process, run_method) self._cleanup_process(process, run_method) self.cleanup_runner() def OnExit(self, event): if self.exit_b.GetLabel()=='Stop': self.interrupt_runner() return while self.process_list: self.terminate_runner() try: values, args = self.option_parser.parse_options_args self.set_result() values, args = self.option_parser.get_result(values) #self.option_parser.save_options(values, args) except optparse.OptionValueError, msg: print 'Ignoring %s' % (msg) pass self.restore_std_streams() self.Close(True) sys.exit(0) def OnRun(self, event): self.start_runner() def OnCloseWindow (self, event): while self.process_list: self.terminate_runner() self.restore_std_streams() self.result = None self.Destroy() def OnSelectPath(self, event): option, ctrl = self.browse_option_map[event.GetId()] path = os.path.abspath(ctrl.Value) if option.type == 'file': if os.path.isdir (path): default_file = '' default_dir = path else: default_file = path default_dir =os.path.dirname(path) dlg = wx.FileDialog(self, message = 'Select file for %s' % (option.get_opt_string()), defaultDir = default_dir, defaultFile=default_file) elif option.type == 'directory': if os.path.isfile(path): path = os.path.dirname (path) dlg = wx.DirDialog(self, message = 'Select directory for %s' % (option.get_opt_string()), defaultPath = path) else: raise NotImplementedError(`option.type`) if dlg.ShowModal() != wx.ID_OK: return cwd = os.path.abspath(os.getcwd()) value = dlg.GetPath() if value.startswith(cwd): value = value[len(cwd)+1:] ctrl.Value = value def set_result(self): option_values = {} for option, ctrl in self.option_controls.iteritems(): value = getattr(ctrl,'Value',None) if value != '' and value is not None: value = get_fixed_option_value(option, value) option_values[option] = value elif value is not None: option_values[option] = None args_buff = str(self.args_ctrl.GetValue()) args = splitcommandline(args_buff) self.option_parser.result = option_values, args def put_result(self): option_values, args = self.option_parser.result for option, ctrl in self.option_controls.iteritems(): value = option_values.get(option) if value is not None: ctrl.SetValue(value) self.args_ctrl.SetValue(' '.join(args)) class UserCancelledError( Exception ): pass def check_file(option, opt, value): try: value = str(value) except ValueError: raise OptionValueError( _("option %s: invalid %s value: %r") % (opt, what, value)) #if value and not os.path.isfile(value): # print 'Warning: path %r is not a file' % (value) return value def check_directory(option, opt, value): try: value = str(value) except ValueError: raise OptionValueError( _("option %s: invalid %s value: %r") % (opt, what, value)) #if value and not os.path.isdir(value): # print 'Warning: path %r is not a directory' % (value) return value class Option(optparse.Option): """Extends optparse.Option with file, directory and multiline types. """ _SUPER = optparse.Option TYPES = _SUPER.TYPES + ('file', 'directory', 'multiline') TYPE_CHECKER = _SUPER.TYPE_CHECKER.copy() TYPE_CHECKER.update (file=check_file, directory=check_directory) class OptionParser( optparse.OptionParser ): """Extends optparse.OptionParser with GUI support. """ _SUPER = optparse.OptionParser """Holds base class. """ def __init__( self, *args, **kwargs ): if 'option_class' not in kwargs: kwargs['option_class'] = Option self.runner = None self._SUPER.__init__( self, *args, **kwargs ) def save_option_value (self, dest, value): return self._set_dest_value (dest, value) def _set_dest_value(self, dest, value, old_cwd = None): if value is None: return option = ([option for option in self._get_all_options () if option.dest == dest] + [None])[0] if option is None: print 'Could not find option with dest=%r for setting %r (dest not specified for option).' % (dest, value) else: if option.type in ['file', 'directory']: if old_cwd is not None: value = os.path.join(old_cwd, value) else: value = os.path.abspath(value) cwd = os.getcwd() if value.startswith(cwd): value = value[len(cwd)+1:] if value == 'none': value = None else: try: option.check_value(option.dest, str(value)) except optparse.OptionValueError, msg: print '_set_dest_value: ignoring %s' % msg return option.default = value if value is None: try: del self.defaults[dest] except KeyError: pass else: self.defaults[dest] = value def get_history_file(self): import hashlib script_history = os.path.join(os.environ.get('HOME',''), '.optparse_history', os.path.basename(sys.argv[0]) + hashlib.md5(os.path.abspath(sys.argv[0])).hexdigest()) return script_history def save_options (self, values, args): script_history = self.get_history_file() if debug>1: print 'Saving options to', script_history cwd = os.path.abspath(os.getcwd()) dirname = os.path.dirname(script_history) if not os.path.isdir (dirname): os.makedirs(dirname) tmp_file = tempfile.mktemp() f = open(tmp_file, 'w') f.write ('#cwd:%r\n' % (cwd)) f.write ('#args:%r\n' % (args,)) for option in self._get_all_options(): if option.dest: value = getattr(values, option.dest, None) if value is not None: f.write('%s: %r\n' % (option.dest, value)) f.close() shutil.move(tmp_file, script_history) def load_options(self): script_history = self.get_history_file () if debug>1: print 'Loading options from',script_history h_args = None h_cwd = None cwd = os.path.abspath(os.getcwd()) if os.path.isfile(script_history): f = open (script_history) for line in f.readlines(): try: dest, value = line.split(':', 1) value = eval(value) except Exception, msg: print 'optparse_gui.load_options: failed parsing options file, line=%r: %s' % (line, msg) continue if dest=='#args': h_args = value elif dest=='#cwd': h_cwd = value else: self._set_dest_value(dest, value, h_cwd) f.close() return h_args def parse_args( self, args = None, values = None ): '''Parse the command-line options. ''' # load options history h_args = self.load_options() no_gui = '--no-gui' in sys.argv if no_gui: sys.argv.remove('--no-gui') # preprocess command line arguments and set to defaults pp_option_values, pp_args = self._SUPER.parse_args(self, args, values) if no_gui: self.save_options(pp_option_values, pp_args) return pp_option_values, pp_args for dest, value in pp_option_values.__dict__.iteritems(): self._set_dest_value(dest, value) self.parse_options_args = (values, args) app = wx.App(redirect=False) try: dlg = OptparseFrame(self) except Exception, msg: traceback.print_exc(file=sys.stdout) raise if pp_args: dlg.args_ctrl.Value = ' '.join(pp_args) elif h_args is not None: dlg.args_ctrl.Value = ' '.join(h_args) dlg.Show (True) app.MainLoop() if self.result is None: print 'User has cancelled, exiting.' sys.exit(0) values, args = self.get_result(values) self.save_options(values, args) return values, args def error( self, msg ): print "AN ERROR OCCURRED WITH A MESSAGE: %s" % (msg) #app = wx.GetApp() #print app, msg #if app is None: # app = wx.App( False ) #wx.MessageDialog( None, msg, 'Error!', wx.ICON_ERROR ).ShowModal() return self._SUPER.error( self, msg ) def get_result(self, values): if values is None: values = self.get_default_values() option_values, args = self.result for option, value in option_values.iteritems(): if option.action=='store_true': if isinstance(value, bool): setattr( values, option.dest, value ) continue if option.action=='store_false': if isinstance(value, bool): setattr( values, option.dest, not value ) continue if option.takes_value() is False: value = None option.process( option, value, values, self ) return values, args ################################################################################ def sample_parse_args(): usage = "usage: %prog [options] args" if 1 == len( sys.argv ): option_parser_class = OptionParser else: option_parser_class = optparse.OptionParser parser = option_parser_class( usage = usage, version='0.1' ) parser.add_option("-f", "--file", dest="filename", default = r'c:\1.txt', help="read data from FILENAME") parser.add_option("-t", "--text", dest="text", default = r'c:\1.txt', help="MULTILINE text field") parser.add_option("-a", "--action", dest="action", choices = ['delete', 'copy', 'move'], help="Which action do you wish to take?!") parser.add_option("-n", "--number", dest="number", default = 23, type = 'int', help="Just a number") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help = 'To be or not to be? ( verbose )' ) (options, args) = parser.parse_args() return options, args def sample_parse_args_issue1(): usage = "usage: %prog [options] args" option_parser_class = OptionParser parser = option_parser_class( usage = usage, version='0.1' ) parser.add_option("-f", "--file", dest="filename", default = r'c:\1.txt', type = 'file', help="read data from FILENAME") parser.add_option("-t", "--text", dest="text", default = r'c:\1.txt', type = 'multiline', help="MULTILINE text field") parser.add_option("-a", "--action", dest="action", choices = ['delete', 'copy', 'move'], help="Which action do you wish to take?!") parser.add_option("-n", "--number", dest="number", default = 23, type = 'int', help="Just a number") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help = 'To be or not to be? ( verbose )' ) group = optparse.OptionGroup(parser, "Dangerous Options", "Caution: use these options at your own risk. " "It is believed that some of them bite.") group.add_option("-g", action="store_true", help="Group option.", ) parser.add_option_group(group) (options, args) = parser.parse_args() return options, args def main(): options, args = sample_parse_args_issue1() print 'args: %s' % repr( args ) print 'options: %s' % repr( options ) if '__main__' == __name__: main() pylibtiff-0.3.0~svn78/libtiff/__init__.py0000664000175100017510000000115311651465222017352 0ustar tilletille"""LibTiff - a Python TIFF library .. currentmodule:: libtiff .. autosummary:: TIFF TIFFfile TiffArray TiffFile TiffFiles TiffChannelsAndFiles """ __autodoc__ = ['libtiff_ctypes', 'tiff', 'tiff_file', 'tiff_files', 'tiff_channels_and_files'] __all__ = ['TIFF', 'TIFFfile', 'TiffArray', 'TiffFile', 'TiffFiles', 'TiffChannelsAndFiles', 'TiffBase'] from .libtiff_ctypes import libtiff, TIFF from .tiff import TIFFfile, TIFFimage, TiffArray from .tiff_file import TiffFile from .tiff_files import TiffFiles from .tiff_channels_and_files import TiffChannelsAndFiles from .tiff_base import TiffBase pylibtiff-0.3.0~svn78/libtiff/tiff_data.py0000664000175100017510000001507011475145413017540 0ustar tilletille""" Defines data for TIFF manipulations. """ __all__ = ['type2name', 'name2type', 'type2bytes', 'type2dtype', 'tag_value2name', 'tag_name2value', 'tag_value2type', 'LittleEndianNumpyDTypes', 'BigEndianNumpyDTypes', 'default_tag_values', 'sample_format_map'] import numpy # tag_info = ''' # standard tags: NewSubfileType FE LONG 1 SubfileType FF SHORT 1 ImageWidth 100 SHORT|LONG 1 ImageLength 101 SHORT|LONG 1 BitsPerSample 102 SHORT SamplesPerPixel Compression 103 SHORT 1 Uncompressed 1 CCITT1D 2 Group3Fax 3 Group4Fax 4 LZW 5 JPEG 6 PackBits 32773 PhotometricInterpretation 106 SHORT 1 WhiteIsZero 0 BlackIsZero 1 RGB 2 RGBPalette 3 TransparencyMask 4 CMYK 5 YCbCr 6 CIELab 8 Threshholding 107 SHORT 1 CellWidth 108 SHORT 1 CellLength 109 SHORT 1 FillOrder 10A SHORT 1 DocumentName 10D ASCII ImageDescription 10E ASCII Make 10F ASCII Model 110 ASCII StripOffsets 111 SHORT|LONG StripsPerImage Orientation 112 SHORT 1 TopLeft 1 TopRight 2 BottomRight 3 BottomLeft 4 LeftTop 5 RightTop 6 RightBottom 7 LeftBottom 8 SamplesPerPixel 115 SHORT 1 RowsPerStrip 116 SHORT|LONG 1 StripByteCounts 117 LONG|SHORT StripsPerImage MinSampleValue 118 SHORT SamplesPerPixel MaxSampleValue 119 SHORT SamplesPerPixel XResolution 11A RATIONAL 1 YResolution 11B RATIONAL 1 PlanarConfiguration 11C SHORT 1 Chunky 1 Planar 2 PageName 11D ASCII XPosition 11E DOUBLE YPosition 11F DOUBLE FreeOffsets 120 LONG FreeByteCounts 121 LONG GrayResponseUnit 122 SHORT 1 GrayResponseCurve 123 SHORT 2**BitsPerSample T4Options 124 LONG 1 T6Options 125 LONG 1 ResolutionUnit 128 SHORT 1 PageNumber 129 SHORT 2 TransferFunction 12D SHORT (1|SamplesPerPixel)*2**BitsPerSample Software 131 ASCII DateTime 132 ASCII 20 Artist 13B ASCII HostComputer 13C ASCII Predictor 13D SHORT 1 WhitePoint 13E RATIONAL 2 PrimaryChromaticities 13F RATIONAL 6 ColorMap 140 SHORT 3*(2**BitsPerSample) HalftoneHints 141 SHORT 2 TileWidth 142 SHORT|LONG 1 TileLength 143 SHORT|LONG 1 TileOffsets 144 LONG TilesPerImage TileByteCounts 145 SHORT|LONG TilesPerImage InkSet 14C SHORT 1 InkNames 14D ASCII NumberOfInks 14E SHORT 1 DotRange 150 BYTE|SHORT 2|2*NumberOfInks TargetPrinter 151 ASCII any ExtraSamples 152 BYTE SampleFormat 153 SHORT SamplesPerPixel SMinSampleValue 154 Any SamplesPerPixel SMaxSampleValue 155 Any SamplesPerPixel TransferRange 156 SHORT 6 JPEGProc 200 SHORT 1 JPEGInterchangeFormat 201 LONG 1 JPEGInterchangeFormatLength 202 LONG 1 JPEGRestartInterval 203 SHORT 1 JPEGLosslessPredictos 205 SHORT SamplesPerPixel JPEGPointTransforms 206 SHORT SamplesPerPixel JPEGQTables 207 LONG SamplesPerPixel JPEGDCTables 208 LONG SamplesPerPixel JPEGACTables 209 LONG SamplesPerPixel YCbCrCoefficients 211 RATIONAL 3 YCbCrSubSampling 212 SHORT 2 YCbCrPositioning 213 SHORT 1 ReferenceBlackWhite 214 LONG 2*SamplesPerPixel Copyright 8298 ASCII Any # non-standard tags: CZ_LSMInfo 866C CZ_LSM ''' default_tag_values = dict(BitsPerSample=8, SampleFormat=1, RowsPerStrip=2**32-1, SamplesPerPixel=1, ExtraSamples = None, PlanarConfiguration=1, Compression=1, Predictor = 1, NewSubfileType=0, Orientation = 1, MaxSampleValue = None, MinSampleValue = None, DateTime = None, Artist = None, HostComputer = None, Software = None, ImageDescription = None, DocumentName = None, ResolutionUnit = 2, XResolution = 1, YResolution = 1, FillOrder = 1, XPosition = None, YPosition = None, Make = None, Model = None, Copyright=None,) rational = numpy.dtype([('numer', numpy.uint32), ('denom', numpy.uint32)]) srational = numpy.dtype([('numer', numpy.int32), ('denom', numpy.int32)]) type2name = {1:'BYTE', 2:'ASCII', 3:'SHORT', 4:'LONG', 5:'RATIONAL', # two longs, lsm uses it for float64 6:'SBYTE', 7:'UNDEFINED', 8:'SSHORT', 9:'SLONG', 10:'SRATIONAL', 11:'FLOAT', 12:'DOUBLE', } name2type = dict((v,k) for k,v in type2name.items()) name2type['SHORT|LONG'] = name2type['LONG'] name2type['LONG|SHORT'] = name2type['LONG'] type2bytes = {1:1, 2:1, 3:2, 4:4, 5:8, 6:1, 7:1, 8:2, 9:4, 10:8, 11:4, 12:8} type2dtype = {1:numpy.uint8, 2:numpy.uint8, 3:numpy.uint16, 4:numpy.uint32, 5:rational, 6:numpy.int8, 8:numpy.int16, 9:numpy.int32,10:srational, 11:numpy.float32, 12:numpy.float64} tag_value2name = {} tag_name2value = {} tag_value2type = {} for line in tag_info.split('\n'): if not line or line.startswith('#'): continue if line[0]==' ': pass else: n,h,t = line.split()[:3] h = eval('0x'+h) tag_value2name[h]=n tag_value2type[h]=t tag_name2value[n]=h sample_format_map = {1:'uint', 2:'int', 3:'float', None:'uint', 6:'complex'} class NumpyDTypes: def get_dtype(self, sample_format, bits_per_sample): format = sample_format_map[sample_format] dtypename = '%s%s' % (format, bits_per_sample) return getattr (self, dtypename) class LittleEndianNumpyDTypes(NumpyDTypes): uint8 = numpy.dtype('u1') uint16 = numpy.dtype('>u2') uint32 = numpy.dtype('>u4') uint64 = numpy.dtype('>u8') int8 = numpy.dtype('>i1') int16 = numpy.dtype('>i2') int32 = numpy.dtype('>i4') int64 = numpy.dtype('>i8') float32 = numpy.dtype('>f4') float64 = numpy.dtype('>f8') complex64 = numpy.dtype('>c8') complex128 = numpy.dtype('>c16') @property def type2dt(self): return dict((k,numpy.dtype(v).newbyteorder('>')) for k,v in type2dtype.items()) BigEndianNumpyDTypes = BigEndianNumpyDTypes() pylibtiff-0.3.0~svn78/libtiff/tiff_sample_plane.py0000664000175100017510000002617011511073344021264 0ustar tilletille""" Implements TIFF sample plane. """ # Author: Pearu Peterson # Created: Jan 2011 from __future__ import division import numpy import tif_lzw __all__ = ['TiffSamplePlane'] def set_array(output_array, input_array): dtype = numpy.uint8 numpy.frombuffer(output_array.data, dtype=dtype)[:] = numpy.frombuffer(input_array.data, dtype=dtype) class TiffSamplePlane: """ Image of a single sample in a TIFF image file directory. """ def __init__(self, ifd, sample_index=0): """ Construct TiffSamplePlane instance. Parameters ---------- ifd : `libtiff.tiff_file.IFDEntry` sample_index : int Specify sample index. When None then interpret pixel as a sample. """ self.ifd = ifd self.sample_index = sample_index self.planar_config = planar_config = ifd.get_value('PlanarConfiguration') self.samples_per_pixel = samples_per_pixel = ifd.get_value('SamplesPerPixel') if sample_index is not None and sample_index >= samples_per_pixel: raise IndexError ('sample index %r must be less that nof samples %r' % (sample_index, samples_per_pixel)) pixels_per_row = ifd.get_value('ImageWidth') rows_of_pixels = ifd.get_value('ImageLength') self.shape = (int(rows_of_pixels), int(pixels_per_row)) rows_per_strip = ifd.get_value('RowsPerStrip') strips_per_image = (rows_of_pixels + rows_per_strip - 1) // rows_per_strip rows_per_strip = min(rows_of_pixels, rows_per_strip) self.rows_per_strip = rows_per_strip self.strip_offsets = strip_offsets = ifd.get_value('StripOffsets') self.strip_nbytes = strip_nbytes = ifd.get_value('StripByteCounts') self.sample_format = sample_format = ifd.get_value('SampleFormat') self.bits_per_sample = bits_per_sample = ifd.get_value('BitsPerSample') bits_per_pixel = sum(bits_per_sample) assert bits_per_pixel % 8==0, `bits_per_pixel, bits_per_sample` bytes_per_pixel = bits_per_pixel // 8 if sample_index is None: bytes_per_sample = bytes_per_pixel else: bytes_per_sample = bits_per_sample[sample_index] // 8 bytes_per_row = bytes_per_pixel * pixels_per_row bytes_per_strip = rows_per_strip * bytes_per_row sample_names = ifd.get_sample_names() pixel_dtype = ifd.get_pixel_dtype() sample_offset = 0 if sample_index is None: dtype = pixel_dtype sample_names = ['pixel'] sample_name = 'pixel' else: dtype = ifd.get_sample_dtypes ()[sample_index] sample_name = sample_names[sample_index] if planar_config==1: sample_offset = sum(bits_per_sample[:sample_index]) // 8 bytes_per_row = pixels_per_row * bytes_per_pixel # uncompressed sample_offset = 0 if planar_config==1 or sample_index is None: bytes_per_sample_row = bytes_per_row else: bytes_per_sample_row = bytes_per_row // samples_per_pixel self.dtype = dtype self.pixel_dtype = pixel_dtype self.bytes_per_pixel = bytes_per_pixel self.bytes_per_row = bytes_per_row self.bytes_per_sample_image = bytes_per_sample_row * rows_of_pixels self.uncompressed_bytes_per_strip = bytes_per_strip self.compression = compression = ifd.get_value('Compression') self.sample_name = sample_name self.sample_offset = sample_offset self.bytes_per_sample_row = bytes_per_sample_row self.strips_per_image = strips_per_image self.is_contiguous = compression==1 and ifd.is_contiguous() time = None descr = ifd.get_value('ImageDescription', human=True) if descr is not None: if descr.startswith (' self.shape[0] or index < 0: raise IndexError('Row index %r out of bounds [0,%r]' % (index, self.shape[0]-1)) if self.planar_config==1: # RGBRGB.. strip_index, row_index = divmod(index, self.rows_per_strip) else: # RR..GG..BB.. index2 = self.sample_index * self.shape[0] + index strip_index, row_index = divmod(index2, self.rows_per_strip) start = self.strip_offsets[strip_index] stop = start + self.strip_nbytes[strip_index] if self.compression==1: strip = self.ifd.tiff.data[start:stop] else: compressed_strip = self.ifd.tiff.data[start:stop] if self.compression==5: # lzw strip = tif_lzw.decode(compressed_strip, self.uncompressed_bytes_per_strip) else: raise NotImplementedError (`self.compression`) start = row_index * self.bytes_per_sample_row + self.sample_offset stop = start + self.bytes_per_sample_row + self.sample_offset if isinstance (subindex, tuple): if len(subindex)==1: subindex = subindex[0] if self.planar_config==1: if isinstance(subindex, (int, long)): start = start + subindex * self.bytes_per_pixel stop = start + self.bytes_per_pixel return strip[start:stop].view(dtype=self.pixel_dtype)[self.sample_name][0] row = strip[start:stop].view(dtype=self.pixel_dtype)[self.sample_name] if not row.size: print self.get_topology() else: row = strip[start:stop].view(dtype=self.dtype) if subindex is not None: return row[subindex] return row def get_rows(self, index, subindex=None): if isinstance(index, (int,long)): r = self.get_row (index, subindex=subindex) return r.reshape((1,)+r.shape) if isinstance (index, slice): indices = range (*index.indices(self.shape[0])) for i,j in enumerate(indices): s = self.get_row(j, subindex=subindex) if i==0: r = numpy.empty((len (indices),)+s.shape, dtype=self.dtype) r[i] = s return r if isinstance (index, tuple): if len (index)==1: return self[index[0]] raise NotImplementedError (`index`) def get_image(self): if self.is_contiguous: if self.planar_config==1: start = self.strip_offsets[0] + self.sample_offset stop = self.strip_offsets[-1] + self.strip_nbytes[-1] image =self.ifd.tiff.data[start:stop].view(dtype=self.pixel_dtype) image = image[self.sample_name].reshape (self.shape) return image else: if self.sample_index is None: start = self.strip_offsets[0] else: start = self.strip_offsets[0] + self.sample_index * self.bytes_per_sample_image stop = start + self.bytes_per_sample_image image = self.ifd.tiff.data[start:stop] image = image.view(dtype=self.dtype).reshape(self.shape) return image else: image = numpy.empty((self.bytes_per_sample_image,), dtype=numpy.uint8) offset = 0 for strip_index in range (len (self.strip_offsets)): start = self.strip_offsets[strip_index] stop = start + self.strip_nbytes[strip_index] if self.compression==1: strip = self.ifd.tiff.data[start:stop] else: compressed_strip = self.ifd.tiff.data[start:stop] if self.compression==5: # lzw strip = tif_lzw.decode(compressed_strip, self.uncompressed_bytes_per_strip) else: raise NotImplementedError (`self.compression`) image[offset:offset + strip.nbytes] = strip offset += strip.nbytes image = image.view(dtype=self.dtype).reshape(self.shape) return image def __len__(self): return self.shape[0] def __getitem__(self, index): if isinstance (index, (int, long)): return self.get_row(index) elif isinstance(index, slice): return self.get_image()[index] elif isinstance(index, tuple): if len(index)==0: return self.get_image() if len(index)==1: return self[index[0]] index0 = index[0] if isinstance(index0, (int, long)): return self.get_row(index0, index[1:]) return self.get_image()[index] raise NotImplementedError (`index`) class TiffSamplePlaneLazy(TiffSamplePlane): def __init__ (self, tiff_file_getter): self.tiff_file_getter = tiff_file_getter self.time = None self._ifd = None @property def ifd(self): ifd = self._ifd if ifd is None: tiff = self.tiff_file_getter() assert len (tiff.IFD)==1,`len (tiff.IFD)` self._ifd = ifd = tiff.IFD[0] return ifd @property def strip_offsets (self): return self.ifd.get_value ('StripOffsets') @property def strip_nbytes (self): return self.ifd.get_value ('StripByteCounts') @property def compression(self): return self.ifd.get_value ('Compression') @property def is_contiguous(self): return self.compression==1 and self.ifd.is_contiguous() def copy_attrs(self, other): for attr in ['sample_index', 'planar_config', 'samples_per_pixel','shape', 'rows_per_strip', 'sample_format', 'bits_per_sample', 'dtype', 'pixel_dtype', 'bytes_per_pixel', 'bytes_per_row', 'bytes_per_sample_image', 'uncompressed_bytes_per_strip', 'sample_name', 'sample_offset', 'bytes_per_sample_row', 'strips_per_image' ]: setattr (self, attr, getattr (other, attr)) pylibtiff-0.3.0~svn78/setup.py0000664000175100017510000000615611370362345015344 0ustar tilletille#!/usr/bin/env python CLASSIFIERS = """\ Development Status :: 3 - Alpha Intended Audience :: Science/Research License :: OSI Approved Programming Language :: Python Topic :: Scientific/Engineering Topic :: Software Development Operating System :: Microsoft :: Windows Operating System :: POSIX Operating System :: Unix Operating System :: MacOS """ MAJOR = 0 MINOR = 3 MICRO = 0 ISRELEASED = not True VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) import os if os.path.exists('MANIFEST'): os.remove('MANIFEST') def write_version_py(filename='libtiff/version.py'): cnt = """ # THIS FILE IS GENERATED FROM libtiff/setup.py short_version='%(version)s' version='%(version)s' release=%(isrelease)s if not release: version += '.dev' import os svn_version_file = os.path.join(os.path.dirname(__file__), '__svn_version__.py') svn_entries_file = os.path.join(os.path.dirname(__file__),'.svn', 'entries') if os.path.isfile(svn_version_file): import imp svn = imp.load_module('libtiff.__svn_version__', open(svn_version_file), svn_version_file, ('.py','U',1)) version += svn.version elif os.path.isfile(svn_entries_file): import subprocess try: svn_version = subprocess.Popen(["svnversion", os.path.dirname (__file__)], stdout=subprocess.PIPE).communicate()[0] except: pass else: version += svn_version.strip() print version """ a = open(filename, 'w') try: a.write(cnt % {'version': VERSION, 'isrelease': str(ISRELEASED)}) finally: a.close() def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None,parent_package,top_path) config.add_subpackage('libtiff') config.get_version('libtiff/version.py') config.add_data_files(('libtiff','LICENSE')) return config if __name__=='__main__': from numpy.distutils.core import setup # Rewrite the version file everytime if os.path.exists('libtiff/version.py'): os.remove('libtiff/version.py') write_version_py() setup(name='pylibtiff', #version='0.3-svn', author = 'Pearu Peterson', author_email = 'pearu.peterson@gmail.com', license = 'http://pylibtiff.googlecode.com/svn/trunk/LICENSE', url = 'http://pylibtiff.googlecode.com', download_url = 'http://code.google.com/p/pylibtiff/downloads/', classifiers=filter(None, CLASSIFIERS.split('\n')), description = 'PyLibTiff: a Python tiff library.', long_description = '''\ PyLibTiff? is a Python package that provides the following modules: libtiff - a wrapper of C libtiff library using ctypes. tiff - a numpy.memmap view of tiff files. ''', platforms = ["All"], #packages = ['libtiff'], #package_dir = {'libtiff': 'libtiff'}, configuration = configuration, ) pylibtiff-0.3.0~svn78/LICENSE0000664000175100017510000000275011370362345014633 0ustar tilletilleCopyright (c) 2009-2010 Pearu Peterson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: a. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. c. Neither the name of the PyLibTiff project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pylibtiff-0.3.0~svn78/MANIFEST.in0000664000175100017510000000004311173602045015350 0ustar tilletilleinclude LICENSE include README.txt