Commit 8797516c authored by Hoek, Steven's avatar Hoek, Steven
Browse files

Recent improvements merged, incl. changes to make the code suitable for Python 3

parent 30f0a843
eclipse.preferences.version=1
encoding//formats/bsqraster.py=utf-8
encoding//toolbox/scalelib.py=latin1
import const;
import os.path;
import array;
from raster import Raster
from .const import Const, constants as const
import os.path
import array
from .raster import Raster
from .gridenvelope2d import GridEnvelope2D;
class AsciiGrid(GridEnvelope2D, Raster):
__author__ = "Steven B. Hoek"
class AsciiGrid(Raster, GridEnvelope2D):
"A raster represented by an ASCII file, with extension 'asc'"
# Constants
const.FILEXT = "asc";
const.MAXDIGITSPERCELL = 11;
# Data attributes - assign some dummy values for the mean time
name = "dummy." + const.FILEXT;
_const = None
name = ""
folder = os.getcwd();
"""
ncols = 1;
nrows = 1;
xll = 0.0;
yll = 0.0;
"""
cellsize = 100.0;
nodatavalue = -9999.0;
datatype = const.FLOAT;
......@@ -32,9 +25,15 @@ class AsciiGrid(GridEnvelope2D, Raster):
__digitspercell = 7;
def __init__(self, filepath, *datatype):
# Initialise
DATAFILEXT = const.FILEXT
HEADEREXT = ""
# Module wide constants
self._const = Const()
self._const.FILEXT = "asc";
self._const.MAXDIGITSPERCELL = 6 # 11
self.name = "dummy." + self._const.FILEXT;
# Initialise further
super(AsciiGrid, self).__init__(filepath)
# Retrieve the name from the filepath and assign - incl. extension
self.name = os.path.basename(filepath);
# Also derive the folder
......@@ -50,10 +49,10 @@ class AsciiGrid(GridEnvelope2D, Raster):
def open(self, mode, ncols=1, nrows=1, xll=0.0, yll=0.0, cellsize=100.0, nodatavalue=-9999.0):
# Initialise
super(AsciiGrid, self).open(mode);
# If file does not exist and mode[0] = 'w', create it!
if (mode[0] == 'w') and (not os.path.exists(self.folder + os.path.sep + self.name)):
self.datafile = file(self.folder + os.path.sep + self.name, 'w');
if (mode[0] == 'w') and (not self.file_exists):
self.datafile = open(os.path.join(self.folder, self.name), 'w');
self.__mode = mode;
GridEnvelope2D.__init__(self, ncols, nrows, xll, yll, cellsize, cellsize);
self.cellsize = cellsize;
......@@ -62,8 +61,8 @@ class AsciiGrid(GridEnvelope2D, Raster):
return True;
else:
# Open the file
if os.path.exists(self.folder + os.path.sep + self.name):
self.datafile = open(self.folder + os.path.sep + self.name, mode[0]);
if self.file_exists:
self.datafile = open(os.path.join(self.folder, self.name), mode[0]);
if (mode[0] == 'w'):
# Assign the data attributes
self.ncols = ncols;
......@@ -92,20 +91,20 @@ class AsciiGrid(GridEnvelope2D, Raster):
# TODO: make this case-insensitive!
if (not self.datafile.closed):
hl = self.datafile.readline();
self.ncols = int(hl.replace('ncols', ''));
self.ncols = int(hl.replace(const.NCOLS, ''));
hl = self.datafile.readline();
self.nrows = int(hl.replace('nrows', ''));
self.nrows = int(hl.replace(const.NROWS, ''));
hl = self.datafile.readline();
self.xll = float(hl.replace('xllcorner', ''));
self.xll = float(hl.replace(const.XLLCORNER.lower(), ''));
hl = self.datafile.readline();
self.yll = float(hl.replace('yllcorner', ''));
self.yll = float(hl.replace(const.YLLCORNER.lower(), ''));
hl = self.datafile.readline();
self.cellsize = float(hl.replace('cellsize', ''));
self.cellsize = float(hl.replace(const.CELLSIZE, ''));
hl = self.datafile.readline();
if (self.datatype == const.INTEGER):
self.nodatavalue = int(hl.replace('NODATA_value', ''));
self.nodatavalue = int(hl.replace(const.NODATA_VALUE, ''));
else:
self.nodatavalue = float(hl.replace('NODATA_value', ''));
self.nodatavalue = float(hl.replace(const.NODATA_VALUE, ''));
else:
msg = "File " + self.name + " not found in folder " + self.folder;
raise IOError(msg);
......@@ -141,45 +140,28 @@ class AsciiGrid(GridEnvelope2D, Raster):
return result;
else: raise StopIteration("Attempt to read raster data from a closed file.");
else: raise StopIteration("Attempt to read raster data from an unassigned file.")
except Exception, e:
print "Error: " + str(e);
except Exception as e:
print("Error: " + str(e));
raise StopIteration;
"""
def hasSameExtent(self, obj):
if not isinstance(obj, AsciiGrid):
return False;
if self.ncols != obj.ncols:
return False;
if self.nrows != obj.nrows:
return False;
if abs(self.cellsize - obj.cellsize) > const.epsilon:
return False;
if abs(self.xll - obj.xll) > const.epsilon:
return False;
if abs(self.yll - obj.yll) > const.epsilon:
return False;
else:
return True;
"""
@staticmethod
def getFileExt():
return const.FILEXT;
def getFileExt(self):
return Raster.getDataFileExt()
def writeheader(self):
# Assume that the file is open; write header of the file with all attributes
if (self.datafile != None):
if (not self.datafile.closed):
try:
self.datafile.write("ncols " + str(self.ncols).rjust(const.MAXDIGITSPERCELL + 1) + "\n");
self.datafile.write("nrows " + str(self.nrows).rjust(const.MAXDIGITSPERCELL + 1) + "\n");
self.datafile.write("xllcorner " + str(self.xll).rjust(const.MAXDIGITSPERCELL + 1) + "\n");
self.datafile.write("yllcorner " + str(self.yll).rjust(const.MAXDIGITSPERCELL + 1) + "\n");
self.datafile.write("cellsize " + str(self.cellsize).rjust(const.MAXDIGITSPERCELL + 1) + "\n");
self.datafile.write("NODATA_value " + str(self.nodatavalue).rjust(const.MAXDIGITSPERCELL + 1) + "\n");
except Exception, e:
print e;
maxdigits = self._const.MAXDIGITSPERCELL + 1
self.datafile.write(const.NCOLS + " " + str(self.ncols).rjust(maxdigits) + "\n");
self.datafile.write(const.NROWS + " " + str(self.nrows).rjust(maxdigits) + "\n");
self.datafile.write(const.XLLCORNER.lower() + " " + str(self.xll).rjust(maxdigits) + "\n");
self.datafile.write(const.YLLCORNER.lower() + " " + str(self.yll).rjust(maxdigits) + "\n");
self.datafile.write(const.CELLSIZE + " " + str(self.cellsize).rjust(maxdigits) + "\n");
self.datafile.write(const.NODATA_VALUE + " " + str(self.nodatavalue).rjust(maxdigits) + "\n");
except Exception as e:
print(e);
msg = "Header lines could not be written to file " + self.name + " in folder " + self.folder;
raise IOError(msg);
......@@ -190,17 +172,17 @@ class AsciiGrid(GridEnvelope2D, Raster):
if (self.datatype == const.INTEGER):
# TODO deal with numpy arrays if necessary
for k in range(0, self.ncols):
s = str(sequence_with_data[k]).rjust(const.MAXDIGITSPERCELL + 1);
s = str(sequence_with_data[k]).rjust(self._const.MAXDIGITSPERCELL + 1);
self.datafile.write(s);
else:
totalwidth = const.MAXDIGITSPERCELL - 1
totalwidth = self._const.MAXDIGITSPERCELL - 1
fmtstr = "{:" + str(totalwidth) + ".2f}"
for k in range(0, self.ncols):
s = fmtstr.format(sequence_with_data[k]).rjust(const.MAXDIGITSPERCELL + 1);
s = fmtstr.format(sequence_with_data[k]).rjust(self._const.MAXDIGITSPERCELL + 1);
self.datafile.write(s);
return self.datafile.write("\n");
except Exception, e:
print e;
except Exception as e:
print(e);
raise StopIteration
def flush(self):
......
# Copyright (c) 2004-2015 Alterra, Wageningen-UR
# Steven Hoek (steven.hoek@wur.nl), June 2015
from raster import Raster
from gridenvelope2d import GridEnvelope2D
from .const import Const, constants as const
from .raster import Raster
from .gridenvelope2d import GridEnvelope2D
import os.path
from math import fabs
__author__ = "Steven B. Hoek"
# Abstract class
class BandRaster(GridEnvelope2D, Raster):
# Constants
INTEL = 'I'; # Least significant byte first
UNSIGNEDINT = 'UNSIGNEDINT'
class BandRaster(Raster, GridEnvelope2D):
# Attributes
_const = None
# Data attributes
nbands = 3 #default
nbits = 8 #default
nodatavalue = 256; #default
dataformat = "h" # Default data format (2-byte signed short int)
folder = os.getcwd();
def __init__(self, filepath, *dataformat):
# Class and subclass wide constants
self._const = Const()
self._const.INTEL = 'I'; # Least significant byte first
self._const.UNSIGNEDINT = 'UNSIGNEDINT'
self._const.PIXELTYPE = 'PIXELTYPE'
self._const.NODATA = 'NODATA'
# Initialise
Raster.__init__(self, filepath)
# Retrieve the name from the filepath and assign - incl. extension
self.name = os.path.basename(filepath);
......@@ -38,19 +47,19 @@ class BandRaster(GridEnvelope2D, Raster):
self.nodatavalue = nodatavalue
self.envelope = GridEnvelope2D.__init__(self, ncols, nrows, xll, yll, cellsize, cellsize)
self.writeheader()
if (not os.path.exists(self.folder + os.path.sep + self.name)):
self.datafile = file(self.folder + os.path.sep + self.name, 'w') # File does not exist
if not self.file_exists:
self.datafile = open(os.path.join(self.folder, self.name), 'w')
else:
self.datafile = open(self.folder + os.path.sep + self.name, mode[0] + 'b') # File exists
self.datafile = open(os.path.join(self.folder, self.name), mode[0] + 'b')
return True
else:
# Open the file
if os.path.exists(os.path.join(self.folder, self.name)):
if self.file_exists:
# Open the file and retrieve the data attributes from the header file
self.datafile = open(self.folder + os.path.sep + self.name, mode[0] + 'b');
self.datafile = open(os.path.join(self.folder, self.name), mode[0] + 'b');
self.readheader();
self.xll = self.xul;
if self.ycoords_sort == 'DESC':
if self.ycoords_sort == const.DESC:
self.yll = self.yul - self.nrows * self.dy;
else:
self.yll = self.yul + self.nrows * self.dy;
......@@ -61,12 +70,12 @@ class BandRaster(GridEnvelope2D, Raster):
def readheader(self):
# See if we can find the header file to use. Then read it and assign all attributes
hdrFilename = ""
if os.path.isfile(os.path.join(self.folder, self.name + "." + self.HEADEREXT)): #@UndefinedVariable
hdrFilename = os.path.join(self.folder, self.name + "." + self.HEADEREXT) #@UndefinedVariable
if os.path.isfile(os.path.join(self.folder, self.name + "." + const.HEADEREXT)): #@UndefinedVariable
hdrFilename = os.path.join(self.folder, self.name + "." + const.HEADEREXT) #@UndefinedVariable
else:
name_wo_ext = os.path.splitext(os.path.join(self.folder, self.name))[0]
if os.path.isfile(name_wo_ext + "." + self.HEADEREXT ): #@UndefinedVariable
hdrFilename = os.path.join(name_wo_ext + "." + self.HEADEREXT) #@UndefinedVariable
if os.path.isfile(name_wo_ext + "." + const.HEADEREXT ): #@UndefinedVariable
hdrFilename = os.path.join(name_wo_ext + "." + const.HEADEREXT) #@UndefinedVariable
if hdrFilename == "":
raise ValueError("Not sure about name of header file: " + hdrFilename + "?");
hdrFilename = os.path.normpath(hdrFilename)
......@@ -75,18 +84,18 @@ class BandRaster(GridEnvelope2D, Raster):
hf = open(hdrFilename, 'r');
if (hf != None):
hl = hf.readline();
self.byteorder = str(hl.replace('BYTEORDER', '').strip());
if self.byteorder != self.INTEL:
self.byteorder = str(hl.replace(const.BYTEORDER, '').strip());
if self.byteorder != self._const.INTEL:
raise ValueError("Unsupported byte order")
hl = hf.readline();
layout = str(hl.replace('LAYOUT', '').strip());
extuc = self.DATAFILEXT.upper()
extuc = self._const.DATAFILEXT.upper()
if layout != extuc:
raise ValueError("Incorrect layout in header - apparently not a " + extuc + " file");
hl = hf.readline();
self.nrows = int(hl.replace('NROWS', ''));
self.nrows = int(hl.replace(const.NROWS.upper(), ''));
hl = hf.readline();
self.ncols = int(hl.replace('NCOLS', ''));
self.ncols = int(hl.replace(const.NCOLS.upper(), ''));
hl = hf.readline();
self.nbands = int(hl.replace('NBANDS', ''));
hl = hf.readline();
......@@ -100,9 +109,9 @@ class BandRaster(GridEnvelope2D, Raster):
if self.nbands * bandrowbytes != totalrowbytes:
raise ValueError("Incorrect total bytes per row in header");
hl = hf.readline();
if hl.find('PIXELTYPE') != -1:
if hl.find(self._const.PIXELTYPE) != -1:
# Assume ESRI style header
self.pixeltype = str(hl.replace('PIXELTYPE', '').strip());
self.pixeltype = str(hl.replace(self._const.PIXELTYPE, '').strip());
hl = hf.readline();
ulxmap = float(hl.replace('ULXMAP', ''));
hl = hf.readline();
......@@ -118,9 +127,9 @@ class BandRaster(GridEnvelope2D, Raster):
self.yul = ulymap + 0.5*self.dy
hl = hf.readline();
if self.dataformat in ['f', 'd']:
self.nodatavalue = float(hl.replace('NODATA', '').strip());
self.nodatavalue = float(hl.replace(self._const.NODATA, '').strip());
else:
self.nodatavalue = int(hl.replace('NODATA', '').strip());
self.nodatavalue = int(hl.replace(self._const.NODATA, '').strip());
hf.close()
else:
# Assume that the rest of the information has to be read from a world file
......@@ -155,29 +164,29 @@ class BandRaster(GridEnvelope2D, Raster):
def writeheader(self):
# TODO: test!
# Write header file with all attributes
hdrFilename = os.path.join(self.folder, self.name + "." + self.HEADEREXT) #@UndefinedVariable
hdrFilename = os.path.join(self.folder, self.name + "." + const.HEADEREXT) #@UndefinedVariable
hdrFilename = os.path.normpath(hdrFilename)
try:
# Open the file if it exists, otherwise create it
if os.path.exists(hdrFilename):
hf = open(hdrFilename, 'w');
else:
hf = file(hdrFilename, 'w');
hf = open(hdrFilename, 'w');
# Now write all the attributes
hf.write("BYTEORDER " + str(self.byteorder) + "\n")
hf.write("LAYOUT " + self.DATAFILEXT.upper() + "\n")
hf.write("NROWS " + str(self.nrows) + "\n")
hf.write("NCOLS " + str(self.ncols) + "\n")
hf.write(const.BYTEORDER + " " + str(self.byteorder) + "\n")
hf.write("LAYOUT " + self._const.DATAFILEXT.upper() + "\n")
hf.write(const.NROWS.upper() + " " + str(self.nrows) + "\n")
hf.write(const.NCOLS.upper() + " " + str(self.ncols) + "\n")
hf.write("NBANDS " + str(self.nbands) + "\n")
hf.write("NBITS " + str(self.nbits) + "\n")
bandrowbytes = self.nbits * self.ncols / 8
hf.write("BANDROWBYTES " + str(bandrowbytes) + "\n")
hf.write("TOTALROWBYTES " + str(self.nbands * bandrowbytes) + "\n")
if self.dataformat.lower() == 'i':
if self.dataformat.isupper(): hf.write("PIXELTYPE UNSIGNEDINT\n")
else: hf.write("PIXELTYPE SIGNEDINT\n")
else: hf.write("PIXELTYPE FLOAT\n")
if self.dataformat.isupper(): hf.write(self._const.PIXELTYPE + " UNSIGNEDINT\n")
else: hf.write(self._const.PIXELTYPE + " SIGNEDINT\n")
else: hf.write(self._const.PIXELTYPE + " FLOAT\n")
# ulxmap - The x-axis map coordinate of the center of the upper left pixel
ulxmap = self.xll + 0.5*self.dx
......@@ -187,8 +196,8 @@ class BandRaster(GridEnvelope2D, Raster):
hf.write("ULYMAP " + str(ulymap) + "\n");
hf.write("XDIM " + str(self.dx) + "\n");
hf.write("YDIM " + str(self.dy) + "\n");
hf.write("NODATA " + str(self.nodatavalue) + "\n");
except Exception, e:
hf.write(self._const.NODATA + " " + str(self.nodatavalue) + "\n");
except Exception as e:
msg = "Header file " + hdrFilename + " could not be written in folder " + self.folder;
raise IOError(msg + "(" + str(e) + ")");
......@@ -208,7 +217,7 @@ class BandRaster(GridEnvelope2D, Raster):
@staticmethod
def getHeaderFileExt():
return self.HEADEREXT
return const.HEADEREXT
def close(self):
if self.datafile:
......
from raster import Raster
import os
from .raster import Raster
import os.path, sys
from libtiff.libtiff_ctypes import TIFFFieldInfo, TIFFDataType, FIELD_CUSTOM, add_tags
from .const import Const, constants as const
from math import fabs
#from itertools import zip
import numpy as np
class BaseTiffRaster(Raster):
# Constants
DATAFILEXT = "tif";
HEADEREXT = "tfw"; # WORLD_EXT?
__BYTESPERCELL = 4;
__author__ = "Steven B. Hoek"
class BaseTiffRaster(Raster):
# Data attributes - assign some dummy values for the mean time
name = "dummy.tif";
name = "";
folder = os.getcwd();
nodatavalue = -9999.0;
byteorder = 'II'; # Little endian
......@@ -25,44 +26,78 @@ class BaseTiffRaster(Raster):
GdalMetadata = '<GDALMetadata>\n <Item name="RepresentationType" sample="0">ATHEMATIC</Item>\n</GDALMetadata>'
def __init__(self, filepath, *datatype):
pass
# Initialise
super(BaseTiffRaster, self).__init__(filepath)
# Module wide constants
self._const = Const()
self._const.DATAFILEXT = "tif"
self._const.WORLDEXT = "tfw"
self._const.PAGE_NUMBER = b"PageNumber"
self._const.IMAGE_WIDTH = "ImageWidth"
self._const.IMAGE_LENGTH = "ImageLength"
self._const.BITS_PER_SAMPLE = "BitsPerSample"
self._const.SAMPLE_FORMAT = "SampleFormat"
self._const.SAMPLE_PER_PIXEL = "SamplesPerPixel"
self._const.PLANAR_CONFIG = "PlanarConfig"
self._const.ORIENTATION = b"Orientation"
self._const.FILL_ORDER = b"FillOrder"
self._const.COMPRESSION = b"Compression"
self._const.GDAL_NODATA = b"GDAL_NODATA"
self._const.GDAL_METADATA = b"GDAL_METADATA"
self._const.COLORMAP = b"ColorMap"
self._const.PHOTOMETRIC = b"PhotoMetric"
self._const.epsilon = 0.0001
# Retrieve the name from the filepath and assign - incl. extension
if filepath != "":
if os.path.isdir(filepath):
self.name = "dummy." + self._const.DATAFILEXT
raise UserWarning("No filename given! IO from / to: %s" % self.name)
else:
self.name = os.path.basename(filepath)
self.folder = os.path.dirname(filepath);
else:
self.name = "dummy." + self._const.DATAFILEXT
self.folder = os.path.dirname(sys.argv[0])
raise UserWarning("No path given! IO from / to: %s" % self.folder)
def open(self, mode, ncols=1, nrows=1, xll=0.0, yll=0.0, cellsize=1.0, nodatavalue=-9999.0):
super(BaseTiffRaster, self).open(mode)
extra_tags = [
TIFFFieldInfo(297, 2, 2, TIFFDataType.TIFF_SHORT, FIELD_CUSTOM, True, False, "PageNumber"),
TIFFFieldInfo(33550, 3, 3, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, "ModelPixelScaleTag"),
TIFFFieldInfo(33922, 6, 6, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, "ModelTiepointTag"),
TIFFFieldInfo(34264, 16, 16, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, "ModelTransformationTag"),
TIFFFieldInfo(34735, 32, 32, TIFFDataType.TIFF_SHORT, FIELD_CUSTOM, True, False, "GeoKeyDirectoryTag"),
TIFFFieldInfo(34736, -1, -1, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, "GeoDoubleParamsTag"),
TIFFFieldInfo(34737, -1, -1, TIFFDataType.TIFF_ASCII, FIELD_CUSTOM, True, False, "GeoAsciiParamsTag"),
TIFFFieldInfo(42112, -1, -1, TIFFDataType.TIFF_ASCII, FIELD_CUSTOM, True, False, "GDAL_METADATA"),
TIFFFieldInfo(42113, -1, -1, TIFFDataType.TIFF_ASCII, FIELD_CUSTOM, True, False, "GDAL_NODATA")
TIFFFieldInfo(297, 2, 2, TIFFDataType.TIFF_SHORT, FIELD_CUSTOM, True, False, self._const.PAGE_NUMBER),
TIFFFieldInfo(33550, 3, 3, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, b"ModelPixelScaleTag"),
TIFFFieldInfo(33922, 6, 6, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, b"ModelTiepointTag"),
TIFFFieldInfo(34264, 16, 16, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, b"ModelTransformationTag"),
TIFFFieldInfo(34735, 32, 32, TIFFDataType.TIFF_SHORT, FIELD_CUSTOM, True, False, b"GeoKeyDirectoryTag"),
TIFFFieldInfo(34736, -1, -1, TIFFDataType.TIFF_DOUBLE, FIELD_CUSTOM, True, False, b"GeoDoubleParamsTag"),
TIFFFieldInfo(34737, -1, -1, TIFFDataType.TIFF_ASCII, FIELD_CUSTOM, True, False, b"GeoAsciiParamsTag"),
TIFFFieldInfo(42112, -1, -1, TIFFDataType.TIFF_ASCII, FIELD_CUSTOM, True, False, self._const.GDAL_METADATA),
TIFFFieldInfo(42113, -1, -1, TIFFDataType.TIFF_ASCII, FIELD_CUSTOM, True, False, self._const.GDAL_NODATA)
]
add_tags(extra_tags)
def set_extra_tags(self):
# The following is in view of the georeferencing
self.datafile.SetField("PageNumber", self.pageNumber)
self.datafile.SetField("ModelPixelScaleTag", self.modelPixelScale)
self.datafile.SetField("ModelTiepointTag", self.modelTiepoint)
self.datafile.SetField("ModelTransformationTag", self.ModelTransformation)
self.datafile.SetField("GeoKeyDirectoryTag", self.GeoKeyDirectory)
self.datafile.SetField(self._const.PAGE_NUMBER, self.pageNumber)
self.datafile.SetField(b"ModelPixelScaleTag", self.modelPixelScale)
self.datafile.SetField(b"ModelTiepointTag", self.modelTiepoint)
self.datafile.SetField(b"ModelTransformationTag", self.ModelTransformation)
self.datafile.SetField(b"GeoKeyDirectoryTag", self.GeoKeyDirectory)
#self.datafile.SetField("GeoDoubleParamsTag", self.GeoDoubleParams)
self.datafile.SetField("GeoAsciiParamsTag", str(self.GeoAsciiParams))
self.datafile.SetField("GDAL_METADATA", str(self.GdalMetadata))
self.datafile.SetField(b"GeoAsciiParamsTag", str(self.GeoAsciiParams))
self.datafile.SetField(self._const.GDAL_METADATA, str(self.GdalMetadata))
def get_extra_tags(self):
# The following is in view of the georeferencing
self.pageNumber = self.datafile.GetField("PageNumber")
self.modelPixelScale = self.datafile.GetField("ModelPixelScaleTag")
self.modelTiepoint = self.datafile.GetField("ModelTiepointTag")
self.ModelTransformation = self.datafile.GetField("ModelTransformationTag")
self.GeoKeyDirectory = self.datafile.GetField("GeoKeyDirectoryTag")
self.pageNumber = self.datafile.GetField(self._const.PAGE_NUMBER)
self.modelPixelScale = self.datafile.GetField(b"ModelPixelScaleTag")
self.modelTiepoint = self.datafile.GetField(b"ModelTiepointTag")
self.ModelTransformation = self.datafile.GetField(b"ModelTransformationTag")
self.GeoKeyDirectory = self.datafile.GetField(b"GeoKeyDirectoryTag")
#self.GeoDoubleParams = self.datafile.GetField("GeoDoubleParamsTag")
self.GeoAsciiParams = self.datafile.GetField("GeoAsciiParamsTag")
self.GdalMetadata = self.datafile.GetField("GDAL_METADATA")
self.GeoAsciiParams = self.datafile.GetField(b"GeoAsciiParamsTag")
self.GdalMetadata = self.datafile.GetField(self._const.GDAL_METADATA)
def copy_extra_tags(self, rg):
# Check input
......@@ -79,4 +114,80 @@ class BaseTiffRaster(Raster):
self.GeoAsciiParams = rg.GeoAsciiParams
self.GdalMetadata = rg.GdalMetadata
\ No newline at end of file
def readheader(self):
# Header has 6 lines - without labels!
sign = lambda x: (1, -1)[x<0];
pos = str.rfind(str(self.name), "." + self._const.DATAFILEXT);
if pos != -1: hdrFilename = self.name[0:pos] + "." + self._const.WORLDEXT
else: raise ValueError("Invalid file name: " + self.name);
if os.path.exists(os.path.join(self.folder, hdrFilename)):
# Adapt the following so that it accounts also for rotated mapsheets
hf = open(os.path.join(self.folder, hdrFilename), 'r');
hl = hf.readline();
self.dx = float(hl.strip());
hl = hf.readline();
self.roty = float(hl.strip());
hl = hf.readline();
self.rotx = float(hl.strip());
eps = self._const.epsilon
if abs(self.rotx)>eps or abs(self.roty)>eps:
raise NotImplementedError("Cannot handle rotated mapsheets yet!")
hl = hf.readline();
self.dy = fabs(float(hl.strip()));
if sign(float(hl.strip())) == 1.0: self.ycoords_sort = const.ASC
hl = hf.readline();
self.xul = float(hl.strip()) - 0.5 * self.dx;
hl = hf.readline();
self.yul = float(hl.strip()) + 0.5 * self.dy;
hf.close();
else:
msg = "Header file " + hdrFilename + " not found in folder " + self.folder;
raise IOError(msg);
def writeheader(self):
# Write header file with all attributes
pos = str.rfind(str(self.name), "." + self._const.DATAFILEXT);
if pos != -1: hdrFilename = self.name[0:pos] + "." + self._const.WORLDEXT
else: raise ValueError("Invalid file name: " + self.name);
try:
# Open the file if it exists, otherwise create it
if os.path.exists(os.path.join(self.folder, hdrFilename)):
hf = open(os.path.join(self.folder, hdrFilename), 'w');
else:
hf = open(os.path.join(self.folder, hdrFilename), 'w');
# Now write all the attributes
hf.write(str(self.dx) + "\n");
eps = self._const.epsilon
if abs(self.rotx)>eps or abs(self.roty)>eps:
raise NotImplementedError("Cannot handle rotated mapsheets yet!")
hf.write(str(self.rotx) + "\n");
hf.write(str(self.roty) + "\n");
if self.ycoords_sort == const.ASC:
hf.write(str(self.dy) + "\n");