Newer
Older
# -*- coding: utf-8 -*-
"""
/***************************************************************************
EnMAPBox
A QGIS plugin
EnMAP-Box V3
-------------------
begin : 2015-08-20
git sha : $Format:%H$
copyright : (C) 2015 by HU-Berlin
email : bj@geo.hu-berlin.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
import os, sys, re, fnmatch, collections, copy, traceback, six
from qgis.core import *
#os.environ['PATH'] += os.pathsep + r'C:\OSGeo4W64\bin'
from osgeo import gdal, ogr, osr, gdal_array

Benjamin Jakimow
committed
#import console.console_output
#console.show_console()
#sys.stdout = console.console_output.writeOut()
#sys.stderr = console.console_output.writeOut()

Benjamin Jakimow
committed
print('Can not find QGIS instance')

Benjamin Jakimow
committed

Benjamin Jakimow
committed
import code
import codecs
from timeseriesviewer import jp, mkdir, DIR_SITE_PACKAGES, file_search, dprint
site.addsitedir(DIR_SITE_PACKAGES)
#I don't know why, but this is required to run this in QGIS
#todo: still required?
path = os.path.abspath(jp(sys.exec_prefix, '../../bin/pythonw.exe'))
if os.path.exists(path):
multiprocessing.set_executable(path)
sys.argv = [ None ]
#ensure that required non-standard modules are available
import pyqtgraph as pg
class SpatialExtent(QgsRectangle):
def __init__(self, crs, *args):
assert isinstance(crs, QgsCoordinateReferenceSystem)
super(SpatialExtent, self).__init__(*args)
self.mCrs = crs
def setCrs(self, crs):
assert isinstance(crs, QgsCoordinateReferenceSystem)
self.mCrs = crs
def crs(self):
return self.mCrs
def toCrs(self, crs):
assert isinstance(crs, QgsCoordinateReferenceSystem)
if self.mCrs != crs:
trans = QgsCoordinateTransform(self.mCrs, crs)
box = trans.transformBoundingBox(box)
return SpatialExtent(crs, box)
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def __copy__(self):
return SpatialExtent(self.crs(), QgsRectangle(self))
def combineExtentWith(self, *args):
if args is None:
return
elif isinstance(args[0], SpatialExtent):
extent2 = args[0].toCrs(self.crs())
self.combineExtentWith(QgsRectangle(extent2))
else:
super(SpatialExtent, self).combineExtentWith(*args)
def setCenter(self, centerPoint, crs=None):
if crs and crs != self.crs():
trans = QgsCoordinateTransform(crs, self.crs())
centerPoint = trans.transform(centerPoint)
delta = centerPoint - self.center()
self.setXMaximum(self.xMaximum() + delta.x())
self.setXMinimum(self.xMinimum() + delta.x())
self.setYMaximum(self.yMaximum() + delta.y())
self.setYMinimum(self.yMinimum() + delta.y())
def __cmp__(self, other):
if other is None: return 1
def __eq__(self, other):
s = ""
def __sub__(self, other):
raise NotImplementedError()
def __mul__(self, other):
raise NotImplementedError()
from timeseriesviewer.ui.widgets import *
from timeseriesviewer.timeseries import TimeSeries, TimeSeriesDatum, SensorInstrument
columnames = ['date','sensor','ns','nl','nb','image','mask']
def __init__(self, TS, parent=None, *args):
super(QAbstractTableModel, self).__init__()
assert isinstance(TS, TimeSeries)
self.TS = TS
def rowCount(self, parent = QModelIndex()):
return len(self.TS)
def columnCount(self, parent = QModelIndex()):
return len(self.columnames)
def removeRows(self, row, count , parent=QModelIndex()):
self.beginRemoveRows(parent, row, row+count-1)
toRemove = self._data[row:row+count]
for i in toRemove:
self._data.remove(i)
self.endRemoveRows()
def getDateFromIndex(self, index):
if index.isValid():
i = index.row()
if i >= 0 and i < len(self.TS):
return self.TS.getTSDs()[i]
def getTimeSeriesDatumFromIndex(self, index):
if index.isValid():
i = index.row()
if i >= 0 and i < len(self.TS):
return None
def data(self, index, role = Qt.DisplayRole):
return None
value = None
ic_name = self.columnames[index.column()]
TSD = self.getTimeSeriesDatumFromIndex(index)
keys = list(TSD.__dict__.keys())
if role == Qt.DisplayRole or role == Qt.ToolTipRole:
if ic_name == 'name':
value = os.path.basename(TSD.pathImg)
elif ic_name == 'sensor':
if role == Qt.ToolTipRole:
value = TSD.sensor.getDescription()
else:
value = str(TSD.sensor)
elif ic_name == 'date':
value = '{}'.format(TSD.date)
elif ic_name == 'image':
value = TSD.pathImg
elif ic_name == 'mask':
value = TSD.pathMsk
elif ic_name in keys:
value = TSD.__dict__[ic_name]
else:
s = ""
elif role == Qt.BackgroundColorRole:
value = None
elif role == Qt.UserRole:
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
return value
#def flags(self, index):
# return Qt.ItemIsEnabled
def flags(self, index):
if index.isValid():
item = self.getTimeSeriesDatumFromIndex(index)
cname = self.columnames[index.column()]
if cname.startswith('d'): #relative values can be edited
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
else:
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
return flags
#return item.qt_flags(index.column())
return None
def headerData(self, col, orientation, role):
if Qt is None:
return None
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.columnames[col]
elif orientation == Qt.Vertical and role == Qt.DisplayRole:
return col
return None
QAbstractItemModel.__init__(self)
#self.rootItem = TreeItem[]
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def index(self, row, column, parent = QModelIndex()):
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QModelIndex()
def setData(self, index, value, role = Qt.EditRole):
if role == Qt.EditRole:
row = index.row()
return False
return False
def data(self, index, role=Qt.DisplayRole):
data = None
if role == Qt.DisplayRole or role == Qt.EditRole:
data = 'sampletext'
return data
def flags(self, QModelIndex):
return Qt.ItemIsSelectable
def rowCount(self, index=QModelIndex()):
#---------------------------------------------------------------------------
def columnCount(self, index=QModelIndex()):
return 1
class TimeSeriesDatumViewManager(QObject):
def __init__(self, timeSeriesViewer):
assert isinstance(timeSeriesViewer, TimeSeriesViewer)
super(TimeSeriesDatumViewManager, self).__init__()
self.TSV = timeSeriesViewer
self.TSDViews = list()
self.bandViewMananger = self.TSV.bandViewManager
self.bandViewMananger.sigBandViewAdded.connect(self.addBandView)
self.bandViewMananger.sigBandViewRemoved.connect(self.removeBandView)
self.bandViewMananger.sigBandViewVisibility.connect(self.setBandViewVisibility)
self.setExtent(self.TSV.TS.getMaxExtent())
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
self.setMaxTSDViews()
self.setTimeSeries(self.TSV.TS)
self.L = self.TSV.ui.scrollAreaSubsetContent.layout()
self.setSubsetSize(QSize(100,50))
def setSubsetSize(self, size):
assert isinstance(size, QSize)
self.subsetSize = size
for tsdv in self.TSDViews:
tsdv.setSubsetSize(size)
self.adjustScrollArea()
def adjustScrollArea(self):
m = self.L.contentsMargins()
n = len(self.TSDViews)
if n > 0:
refTSDView = self.TSDViews[0]
size = refTSDView.ui.size()
w = n * size.width() + (n-1) * (m.left()+ m.right())
h = max([refTSDView.ui.minimumHeight() + m.top() + m.bottom(),
self.TSV.ui.scrollAreaSubsets.height()-25])
self.L.parentWidget().setFixedSize(w,h)
def setTimeSeries(self,TS):
assert isinstance(TS, TimeSeries)
self.TS = TS
self.TS.sigTimeSeriesDatumAdded.connect(self.createTSDView)
def setMaxTSDViews(self, n=-1):
self.nMaxTSDViews = n
#todo: remove views
def setExtent(self, extent):
self.extent = extent
if extent:
assert isinstance(extent, SpatialExtent)
tsdviews = sorted(self.TSDViews, key=lambda t:t.TSD)
for tsdview in tsdviews:
tsdview.setSpatialExtent(extent)
def navToDOI(self, TSD):
assert isinstance(TSD, TimeSeriesDatum)
#get widget related to TSD
tsdviews = [t for t in self.TSDViews if t.TSD == TSD]
if len(tsdviews) > 0:
i = self.TSDViews.index(tsdviews[0])+1.5
n = len(self.TSDViews)
scrollBar = self.TSV.ui.scrollAreaSubsets.horizontalScrollBar()
smin = scrollBar.minimum()
smax = scrollBar.maximum()
v = smin + (smax - smin) * float(i) / n
scrollBar.setValue(int(round(v)))
def setBandViewVisibility(self, bandView, isVisible):
assert isinstance(bandView, BandView)
assert isinstance(isVisible, bool)
for tsdv in self.TSDViews:
tsdv.ui.setBandViewVisibility(isVisible)
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def addBandView(self, bandView):
assert isinstance(bandView, BandView)
w = self.L.parentWidget()
w.setUpdatesEnabled(False)
for tsdv in self.TSDViews:
tsdv.ui.setUpdatesEnabled(False)
for tsdv in self.TSDViews:
tsdv.insertBandView(bandView)
for tsdv in self.TSDViews:
tsdv.ui.setUpdatesEnabled(True)
w.setUpdatesEnabled(True)
def removeBandView(self, bandView):
assert isinstance(bandView, BandView)
for tsdv in self.TSDViews:
tsdv.removeBandView(bandView)
def createTSDView(self, TSD):
assert isinstance(TSD, TimeSeriesDatum)
tsdView = TimeSeriesDatumView(TSD)
tsdView.setSubsetSize(self.subsetSize)
if self.extent:
tsdView.setSpatialExtent(self.extent)
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
self.addTSDView(tsdView)
def removeTSD(self, TSD):
assert isinstance(TSDV, TimeSeriesDatum)
tsdvs = [tsdv for tsdv in self.TSDViews if tsdv.TSD == TSD]
assert len(tsdvs) == 1
self.removeTSDView(tsdvs[0])
def removeTSDView(self, TSDV):
assert isinstance(TSDV, TimeSeriesDatumView)
self.TSDViews.remove(TSDV)
def addTSDView(self, TSDV):
assert isinstance(TSDV, TimeSeriesDatumView)
if len(self.TSDViews) < 10:
pass
bisect.insort(self.TSDViews, TSDV)
TSDV.ui.setParent(self.L.parentWidget())
self.L.addWidget(TSDV.ui)
self.adjustScrollArea()
#self.TSV.ui.scrollAreaSubsetContent.update()
#self.TSV.ui.scrollAreaSubsets.update()
s = ""

Benjamin Jakimow
committed
class BandView(QObject):
sigAddBandView = pyqtSignal(object)
sigRemoveBandView = pyqtSignal(object)

Benjamin Jakimow
committed
def __init__(self, recommended_bands=None, parent=None, showSensorNames=True):
super(BandView, self).__init__()
self.ui.create()
#forward actions with reference to this band view
self.ui.actionAddBandView.triggered.connect(lambda : self.sigAddBandView.emit(self))
self.ui.actionRemoveBandView.triggered.connect(lambda: self.sigRemoveBandView.emit(self))
self.ui.actionHideBandView.toggled.connect(self.sigHideBandView)
self.sensorViews = collections.OrderedDict()
self.mShowSensorNames = showSensorNames
def setTitle(self, title):
self.ui.labelViewName.setText(title)
def showSensorNames(self, b):
assert isinstance(b, bool)
self.mShowSensorNames = b
for s,w in self.sensorViews.items():
w.showSensorName(b)
def removeSensor(self, sensor):
assert type(sensor) is SensorInstrument
if sensor in self.sensorViews.keys():
self.sensorViews[sensor].close()
self.sensorViews.pop(sensor)
return True
else:
return False
def hasSensor(self, sensor):
assert type(sensor) is SensorInstrument
return sensor in self.sensorViews.keys()
w.showSensorName(self.mShowSensorNames)
self.sensorViews[sensor] = w
l = self.ui.sensorList.layout()
i = l.count() #last widget is a spacer
l.insertWidget(i-1, w.ui)
class BandViewManager(QObject):
sigSensorAdded = pyqtSignal(SensorInstrument)
sigSensorRemoved = pyqtSignal(SensorInstrument)
sigBandViewAdded = pyqtSignal(BandView)
sigBandViewRemoved = pyqtSignal(BandView)
def __init__(self, timeSeriesViewer):
assert isinstance(timeSeriesViewer, TimeSeriesViewer)
super(BandViewManager, self).__init__()
self.TSV = timeSeriesViewer
self.bandViews = []
def removeSensor(self, sensor):
assert isinstance(sensor, SensorInstrument)
removed = False
for view in self.bandViews:
removed = removed and view.removeSensor(sensor)
if removed:
self.sigSensorRemoved(sensor)
def createBandView(self):
bandView = BandView(parent=self.TSV.ui.scrollAreaBandViewsContent, showSensorNames=False)
bandView.sigAddBandView.connect(self.createBandView)
bandView.sigRemoveBandView.connect(self.removeBandView)
bandView.sigHideBandView.connect(lambda b: self.sigBandViewVisibility.emit(bandView, b))
def setBandViewVisibility(self, bandView, isVisible):
assert isinstance(bandView, BandView)
assert isinstance(isVisible, bool)
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def addBandView(self, bandView):
assert isinstance(bandView, BandView)
l = self.TSV.BVP
self.bandViews.append(bandView)
l.addWidget(bandView.ui)
n = len(self)
for sensor in self.TSV.TS.Sensors:
bandView.addSensor(sensor)
bandView.showSensorNames(n == 1)
bandView.setTitle('#{}'.format(n))
self.sigBandViewAdded.emit(bandView)
def removeBandView(self, bandView):
assert isinstance(bandView, BandView)
self.bandViews.remove(bandView)
self.TSV.BVP.removeWidget(bandView.ui)
bandView.ui.close()
#self.TSV.ui.scrollAreaBandViewsContent.update()
if len(self.bandViews) > 0:
self.bandViews[0].showSensorNames(True)
for i, bv in enumerate(self.bandViews):
bv.setTitle('#{}'.format(i + 1))
self.sigBandViewRemoved.emit(bandView)
def __len__(self):
return len(self.bandViews)
def __iter__(self):
return iter(self.bandViews)
def __getitem__(self, key):
return self.bandViews[key]
def __contains__(self, bandView):
return bandView in self.bandViews
class TimeSeriesDatumView(QObject):
def __init__(self, TSD, parent=None):
super(TimeSeriesDatumView, self).__init__()
self.L = self.ui.layout()
self.wOffset = self.L.count()-1
def setBandViewVisibility(self, bandView, isVisible):
self.bandViewCanvases[bandView].setVisible(isVisible)
def setSubsetSize(self, size):
assert isinstance(size, QSize)
assert size.width() > 5 and size.height() > 5
self.subsetSize = size
m = self.L.contentsMargins()
self.ui.labelTitle.setFixedWidth(size.width())
self.ui.line.setFixedWidth(size.width())
#apply new subset size to existing canvases
c.setFixedSize(size)
self.ui.setFixedWidth(size.width() + 2*(m.left() + m.right()))
n = len(self.bandViewCanvases)
#todo: improve size forecast
self.ui.setMinimumHeight((n+1) * size.height())
def setTimeSeriesDatum(self, TSD):
assert isinstance(TSD, TimeSeriesDatum)
self.TSD = TSD
self.ui.labelTitle.setText(str(TSD.date))
c.setLayer(self.TSD.pathImg)
def removeBandView(self, bandView):
self.bandViewOrder.remove(bandView)
canvas = self.bandViewCanvases[bandView]
self.L.removeWidget(canvas)
canvas.close()
def insertBandView(self, bandView, i=-1):
assert isinstance(bandView, BandView)
assert len(self.bandViewCanvases) == len(self.bandViewOrder)
canvas.setLayer(self.TSD.pathImg)
canvas.setFixedSize(self.subsetSize)
self.bandViewCanvases[bandView] = canvas
self.bandViewOrder.insert(i, bandView)
self.L.insertWidget(self.wOffset + i, canvas)
def __lt__(self, other):
return self.TSD < other.TSD
class RenderJob(object):
def __init__(self, TSD, renderer, destinationId=None):
assert isinstance(TSD, TimeSeriesDatum)
assert isinstance(renderer, QgsRasterRenderer)
self.TSD = TSD
self.renderer = renderer
self.destinationId = destinationId
def __eq__(self, other):
if not isinstance(other, RenderJob):
return False
return self.TSD == other.TSD and \
self.renderer == other.renderer and \
self.destinationId == other.destinationId
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
class PixmapBuffer(QObject):
sigProgress = pyqtSignal(int, int)
sigPixmapCreated = pyqtSignal(RenderJob, QPixmap)
def __init__(self):
super(PixmapBuffer, self).__init__()
self.extent = None
self.crs = None
self.size = None
self.nWorkersMax = 1
self.Workers = []
self.PIXMAPS = dict()
self.JOBS = []
self.nTotalJobs = -1
self.nJobsDone = -1
def addWorker(self):
w = Worker()
w.setCrsTransformEnabled(True)
w.sigPixmapCreated.connect(self.newPixmapCreated)
if self.isValid():
self.setWorkerProperties(w)
self.Workers.append(w)
def setWorkerProperties(self, worker):
assert isinstance(worker, Worker)
worker.setFixedSize(self.size)
worker.setDestinationCrs(self.crs)
worker.setExtent(self.extent)
worker.setCenter(self.extent.center())
def newPixmapCreated(self, renderJob, pixmap):
self.JOBS.remove(renderJob)
self.nJobsDone += 1
self.sigPixmapCreated.emit(renderJob, pixmap)
self.sigProgress.emit(self.nJobsDone, self.nTotalJobs)
def isValid(self):
return self.extent != None and self.crs != None and self.size != None
def setExtent(self, extent, crs, maxPx):
self.stopRendering()
assert isinstance(extent, QgsRectangle)
assert isinstance(crs, QgsCoordinateReferenceSystem)
assert isinstance(maxPx, int)
ratio = extent.width() / extent.height()
if ratio < 1: # x is largest side
size = QSize(maxPx, int(maxPx / ratio))
else: # y is largest
size = QSize(int(maxPx * ratio), maxPx)
self.crs = crs
self.size = size
self.extent = extent
for w in self.Workers:
self.setWorkerProperties(w)
return size
def stopRendering(self):
for w in self.Workers:
w.stopRendering()
w.clear()
while len(self.JOBS) > 0:
self.JOBS.pop(0)
self.sigProgress.emit(0, 0)
def loadSubsets(self, jobs):
for j in jobs:
assert isinstance(j, RenderJob)
self.stopRendering()
self.JOBS.extend(jobs)
self.nTotalJobs = len(self.JOBS)
self.nJobsDone = 0
self.sigProgress.emit(0, self.nTotalJobs)
if len(self.Workers) == 0:
self.addWorker()
#split jobs to number of workers
i = 0
chunkSize = int(len(self.JOBS) / len(self.Workers))
assert chunkSize > 0
for i in range(0, len(self.Workers), chunkSize):
worker = self.Workers[i]
j = min(i+chunkSize, len(self.JOBS))
worker.startLayerRendering(self.JOBS[i:j])
class Worker(QgsMapCanvas):
sigPixmapCreated = pyqtSignal(RenderJob, QPixmap)
def __init__(self, *args, **kwds):
super(Worker,self).__init__(*args, **kwds)
self.reg = QgsMapLayerRegistry.instance()
self.painter = QPainter()
self.renderJobs = list()
self.mapCanvasRefreshed.connect(self.createPixmap)
def isBusy(self):
return len(self.renderJobs) != 0
def createPixmap(self, *args):
if len(self.renderJobs) > 0:
pixmap = QPixmap(self.size())
self.painter.begin(pixmap)
self.map().paint(self.painter)
self.painter.end()
assert not pixmap.isNull()
job = self.renderJobs.pop(0)
self.sigPixmapCreated.emit(job, pixmap)
self.startSingleLayerRendering()
def stopLayerRendering(self):
self.stopRendering()
del self.renderJobs[:]
assert self.isBusy() is False
def startLayerRendering(self, renderJobs):
assert isinstance(renderJobs, list)
self.renderJobs.extend(renderJobs)
self.startSingleLayerRendering()
def startSingleLayerRendering(self):
if len(self.renderJobs) > 0:
renderJob = self.renderJobs[0]
assert isinstance(renderJob, RenderJob)
#mapLayer = QgsRasterLayer(renderJob.TSD.pathImg)
mapLayer = renderJob.TSD.lyrImg
mapLayer.setRenderer(renderJob.renderer)
dprint('QgsMapLayerRegistry count: {}'.format(self.reg.count()))
self.reg.addMapLayer(mapLayer)
lyrSet = [QgsMapCanvasLayer(mapLayer)]
self.setLayerSet(lyrSet)
#todo: add crosshair
self.refreshAllLayers()
class ImageChipLabel(QLabel):
clicked = pyqtSignal(object, object)
def __init__(self, time_series_viewer, TSD, renderer):
assert isinstance(time_series_viewer, TimeSeriesViewer)
assert isinstance(TSD, TimeSeriesDatum)
assert isinstance(renderer, QgsRasterRenderer)
super(ImageChipLabel, self).__init__(time_series_viewer.ui)
self.TSD = TSD
self.bn = os.path.basename(self.TSD.pathImg)
self.renderer = renderer
self.setContextMenuPolicy(Qt.DefaultContextMenu)
self.setFrameShape(QFrame.StyledPanel)
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
tt = ['Date: {}'.format(TSD.date) \
,'Name: {}'.format(self.bn) \
def contextMenuEvent(self, event):
menu = QMenu()
#add general options
action = menu.addAction('Copy to clipboard')
action.triggered.connect(lambda : QApplication.clipboard().setPixmap(self.pixmap()))
#add QGIS specific options
if self.TSV.iface:
action = menu.addAction('Add {} to QGIS layers'.format(self.bn))
action.triggered.connect(lambda : qgis_add_ins.add_QgsRasterLayer(self.iface, self.TSD.pathImg, self.bands))
menu.exec_(event.globalPos())
def getBoundingBoxPolygon(points, srs=None):
ring = ogr.Geometry(ogr.wkbLinearRing)
for point in points:
ring.AddPoint(point[0], point[1])
bb = ogr.Geometry(ogr.wkbPolygon)
bb.AddGeometry(ring)
_crs = osr.SpatialReference()
_crs.ImportFromWkt(srs.toWkt())
bb.AssignSpatialReference(_crs)
return bb
def getDS(ds):
if type(ds) is not gdal.Dataset:
ds = gdal.Open(ds)
return ds
def getBandNames(lyr):
assert isinstance(lyr, QgsRasterLayer)
dp = lyr.dataProvider()
assert isinstance(dp, QgsRasterDataProvider)
if str(dp.name()) == 'gdal':
s = ""
else:
return lyr
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
def getImageDate(ds):
if type(ds) is str:
ds = gdal.Open(ds)
path = ds.GetFileList()[0]
to_check = [os.path.basename(path), os.path.dirname(path)]
regAcqDate = re.compile(r'acquisition (time|date|day)', re.I)
for key, value in ds.GetMetadata_Dict().items():
if regAcqDate.search(key):
to_check.insert(0, value)
for text in to_check:
date = parseAcquisitionDate(text)
if date:
return date
raise Exception('Can not identify acquisition date of {}'.format(path))
def getChip3d(chips, rgb_idx, ranges):
assert len(rgb_idx) == 3 and len(rgb_idx) == len(ranges)
for i in rgb_idx:
assert i in chips.keys()
nl, ns = chips[rgb_idx[0]].shape
a3d = np.ndarray((3,nl,ns), dtype='float')
for i, rgb_i in enumerate(rgb_idx):
range = ranges[i]
data = chips[rgb_i].astype('float')
data -= range[0]
data *= 255./range[1]
a3d[i,:] = data
np.clip(a3d, 0, 255, out=a3d)
return a3d.astype('uint8')
def Array2Image(d3d):
nb, nl, ns = d3d.shape
byteperline = nb
d3d = d3d.transpose([1,2,0]).copy()
return QImage(d3d.data, ns, nl, QImage.Format_RGB888)
self.data = dict()
self.BBox = None
self.SRS = None
def hasDataCube(self, TSD):
return TSD in self.data.keys()
missing = missing - set(self.data[TSD].keys())
assert self.BBox is not None, 'Please initialize the bounding box first.'
if TSD not in self.data.keys():
self.data[TSD] = dict()
self.data[TSD].update(chipData)
def getDataCube(self, TSD):
return self.data.get(TSD)
def getChipArray(self, TSD, band_view, mode='rgb'):
assert mode in ['rgb', 'bgr']
bands = band_view.getBands(TSD.sensor)
band_ranges = band_view.getRanges(TSD.sensor)
nb = len(bands)
assert nb == 3 and nb == len(band_ranges)
assert TSD in self.data.keys(), 'Time Series Datum {} is not in buffer'.format(TSD.getDate())
chipData = self.data[TSD]
for b in bands:
assert b in chipData.keys()