[Qgis-user] [pyqgis] looping through a raster
andrea antonello
andrea.antonello at gmail.com
Fri May 5 08:04:00 PDT 2023
I apologize for my previous badly readable code snippet.
Here a better version with a dummy example:
# simple raster stats
cols = dtmLayer.width();
rows = dtmLayer.height();
minV = 10000000
maxV = 0
count = 0
sum = 0
transformType = QgsRasterDataProvider.TransformType.TransformImageToLayer
for row in range(rows):
for col in range(cols):
point = dtmLayer.dataProvider().transformCoordinates(QgsPoint(col, row),
transformType)
value, res = dtmLayer.dataProvider().sample(QgsPointXY(point.x(), point.y()),
1)
if res and value != -9999.0:
minV = min(value, minV)
maxV = max(value, maxV)
count += 1
sum += value
avg = sum/count;
This now works, but looks like it might be very slow for larger rasters..
Thanks,
Andrea
On Fri, May 5, 2023 at 4:48 PM andrea antonello <andrea.antonello at gmail.com>
wrote:
>
> Hello,
> I am trying to understand how to easily loop through the values of a
> raster layer using pyqgis.
>
> In the docs I see the sample and identify methods of the dataprovider,
> but can't spot anything that uses rows/cols as a way of iteration.
> Is the most efficient way to use transformCoordinates to get the world
> coordinates and then use the sample function?
>
> Something like this:
>
> cols = dtmLayer.width();
> rows = dtmLayer.height();
> transformType = QgsRasterDataProvider.TransformType.TransformImageToLayer
> for row in range(rows):
> for col in range(cols):
> point =
> dtmLayer.dataProvider().transformCoordinates(QgsPoint(col, row),
> transformType)
> value, res =
> dtmLayer.dataProvider().sample(QgsPointXY(point.x(), point.y()), 1)
>
> The above for some reason doesn't work yet though.
>
> Thanks,
> Andrea
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20230505/20b91b86/attachment.htm>
More information about the QGIS-User
mailing list