2

My goal is to extract corner coordinates (i.e. UpperLeft, UpperRight, LowerRight, LowerLeft) from polygon extent using PyQGIS or GDAL.

In ArcPy there is a handy property of an extent class (i.e. feature['SHAPE@'].extent.upperLeft), but is there something similar in PyQGIS / GDAL?

2 Answers 2

3

With PyQGIS you can use following code:

layer = iface.activeLayer()

feats = [ feat for feat in layer.getFeatures() ]

for i, feat in enumerate(feats):
    bbox = feat.geometry().boundingBox()
    xmin,ymin,xmax,ymax = bbox.toRectF().getCoords()
    print xmin, ymin, xmax, ymax

Editing Note:

layer = iface.activeLayer()

feats = [ feat for feat in layer.getFeatures() ]

for i, feat in enumerate(feats):
    bbox = feat.geometry().boundingBox()
    xmin,ymin,xmax,ymax = bbox.toRectF().getCoords()
    print xmin, ymin, xmax, ymax
    topLeft = (xmin, ymax)
    bottomRight = (xmax, ymin)

    print topLeft, bottomRight

enter image description here

8
  • It, works, thank you! But is there a way to directly get a proper X, Y pairs for these corners?
    – Basile
    Commented Jan 30, 2018 at 16:41
  • 1
    looks like QRectF has get bottomLeft() and topRight() which return a QPointF - see doc.qt.io/archives/qt-4.8/qrectf.html
    – Ian Turton
    Commented Jan 30, 2018 at 16:51
  • @IanTurton I don't know if it is a bug but 'topLeft()' really produces a botton left point. So, it's preferable to group values produced with 'getCoords' method.
    – xunilk
    Commented Jan 30, 2018 at 17:15
  • @xunilk so this way we could not get real corners of the source geometry, right?
    – Basile
    Commented Jan 30, 2018 at 17:24
  • Are you sure because that would be a hell of a bug
    – Ian Turton
    Commented Jan 30, 2018 at 17:46
2
from osgeo import gdal

ds = gdal.Open(fn)
ulx, width, xrot, uly, yrot, height  = ds.GetGeoTransform()
lrx = ulx + (ds.RasterXSize * width)
lry = uly + (ds.RasterYSize * height)

where: ulx and uly are the upper left corner coordinates and lrx and lry are the lower right corner coordinates.

GetGeoTransform() returns a tuple with the following elements:

  1. Origin x coordinate
  2. Pixel width
  3. x pixel rotation
  4. Origin y coordinate
  5. y pixel rotation
  6. Pixel height

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.