4

I have a problem where for the past few days I've been trying to generate binary black and white images of maps with labeled buildings from a GeoJSON file all programatically with Python.

I need to dimensions to match exactly with the original image (438 x 406). What I've done so far to generate the image below is...

# Imported the image first so the geojson matches with a correct coordinate system
image_layer = iface.addRasterLayer("path\\to\\image", "image_layer")

# Resize to the pixels I need my image as
iface.mapCanvas().resize(QSize(438,406))

# Add geojson object
vector_layer = iface.addVectorLayer("path\\to\\geojson", "geojson_layer", "ogr")

#Set background to black
iface.mapCanvas().setCanvasColor(QColor.fromRgb(0,0,0))

#Then I need to do some code to delete the image_layer

#Render the image
iface.mapCanvas().saveAsImage( IMAGE_DIR + FILENAME + ".png" )

Which then generates an image like this...(or will) enter image description here

But the size is wrong...you can see it when I keep the image layer (see the extra black boundary)

enter image description here

I need it to be the exact same dimmensions as that original image, 438 x 406, but the image it generates is 434 x 402. Even hard coding it down to 434 x 402 then it is just 4 less than that at 430 x 398.

EDIT I tried doing...

iface.mapCanvas().setExtent(image_layer.extent())
iface.mapCanvas().refresh()

But it didn't work.

EDIT2

However, if I do iface.mapCanvas().setExtent(image_layer.extent()) outside of my script (ctrl c ctrl v into the qgis console) it resizes how I want it in QGIS but then saving it still isn't correct. (see below).

enter image description here

EDIT3 When I do the above manually (via the toolbar save as image) it works fine to generate the image below....I just need that done programatically!

enter image description here

mgri
  • 16,159
  • 6
  • 47
  • 80
Carson
  • 355
  • 2
  • 11

1 Answers1

5
iface.mapCanvas().setExtent(raster_layer.extent())
iface.mapCanvas().refresh()
iface.mapCanvas().saveAsImage("img_name.png")

This code works inside QGIS by copy and pasting it into the console after I ran the code above from a script.

This works to generate the image below. Set the extent to the raster layer and then refresh and then save. However, to make it continuous in a script (as in, programmaticaly iterate through geoJSON layers and do this) need to set it up with QTimer so the map properly refreshes. This method works line by line, to avoid the line by line issue see this post about QTimer ... this

enter image description here

Carson
  • 355
  • 2
  • 11