QGIS/python/plugins/processing/core/RasterWriter.py

74 lines
2.4 KiB
Python
Raw Normal View History

2013-01-26 23:55:14 +01:00
# -*- coding: utf-8 -*-
"""
***************************************************************************
2013-08-12 20:44:27 +02:00
RasterWriter.py
2013-01-26 23:55:14 +01:00
---------------------
Date : January 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'September 2012'
__copyright__ = '(C) 2012, Victor Olaya'
2013-01-26 23:55:14 +01:00
# This will get replaced with a git SHA1 when you do a git archive
2013-01-26 23:55:14 +01:00
__revision__ = '$Format:%H$'
import numpy
2013-02-03 10:27:42 +01:00
from osgeo import gdal
from osgeo import osr
from PyQt4.QtCore import *
from qgis.core import *
2013-01-26 23:55:14 +01:00
2013-08-12 20:44:27 +02:00
class RasterWriter:
2013-01-26 23:55:14 +01:00
NODATA = -99999.0
2013-02-07 01:09:39 +01:00
def __init__(self, fileName, minx, miny, maxx, maxy, cellsize,
nbands, crs):
2013-01-26 23:55:14 +01:00
self.fileName = fileName
2013-02-03 10:27:42 +01:00
self.nx = int((maxx - minx) / float(cellsize))
self.ny = int((maxy - miny) / float(cellsize))
self.nbands = nbands
2013-02-03 10:27:42 +01:00
self.matrix = numpy.ones(shape=(self.ny, self.nx), dtype=numpy.float32)
2013-01-26 23:55:14 +01:00
self.matrix[:] = self.NODATA
self.cellsize = cellsize
2013-02-07 01:09:39 +01:00
self.crs = crs
2013-02-03 10:27:42 +01:00
self.minx = minx
2013-02-07 01:09:39 +01:00
self.maxy = maxy
def setValue(self, value, x, y, band=0):
2013-01-26 23:55:14 +01:00
try:
2013-02-03 10:27:42 +01:00
self.matrix[y, x] = value
2013-01-26 23:55:14 +01:00
except IndexError:
pass
2013-02-07 01:09:39 +01:00
def getValue(self, x, y, band=0):
2013-01-26 23:55:14 +01:00
try:
2013-02-03 10:27:42 +01:00
return self.matrix[y, x]
2013-01-26 23:55:14 +01:00
except IndexError:
2013-02-07 01:09:39 +01:00
return self.NODATA
2013-01-26 23:55:14 +01:00
def close(self):
format = 'GTiff'
driver = gdal.GetDriverByName(format)
dst_ds = driver.Create(self.fileName, self.nx, self.ny, 1,
gdal.GDT_Float32)
2013-02-03 10:27:42 +01:00
dst_ds.SetProjection(str(self.crs.toWkt()))
dst_ds.SetGeoTransform([self.minx, self.cellsize, 0,
self.maxy, self.cellsize, 0])
2013-02-03 10:27:42 +01:00
dst_ds.GetRasterBand(1).WriteArray(self.matrix)
dst_ds = None