I have the following problem:

The following sequence of operations:

  1. loading a shp file using a gdal package,
  2. extracting a layer out of it (every feature in this layer is a polygon),

leads me to a place where rasterizing every feature in its own extent to a separate numpy.array seems to be an impossible task.

Is there any way to achieve that without hacking a osg package in a really cumbersome way?

  • You can extract and combine what you want from a Numpy array (Map algebra) – gene Dec 20 '16 at 17:18
  • Goodday everyone. Pls, I would like to create an offline android app that can read arcmap (arcgis) shapefiles and generate the maps as created on arcgis. I tend using python for it. How do I go about it? Thanks in anticipation – Anthony Ifeanyi May 5 at 12:22
  • If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review – Dan C May 5 at 13:16

You can use fiona to read the shapefile, and rasterio to rasterize the geometries. The example below returns a list of numpy arrays containing each the rasterized output the feature.

import urllib
import zipfile

import fiona
from rasterio import features
from affine import Affine

# Download data
urllib.urlretrieve("http://biogeo.ucdavis.edu/data/gadm2.8/shp/BLZ_adm_shp.zip", "belize.zip")

# Extract data
with zipfile.ZipFile('belize.zip', 'r') as con:

# Read shapefile and raterize each of its features
with fiona.open('BLZ_adm1.shp') as src:
    np_list = [features.rasterize([geom['geometry']], out_shape=(500,500), transform=Affine(0.01, 0.0, -90.0, 0, -0.01, 18.0)) for geom in src]

To have them all in a single 3D array

import numpy as np

with fiona.open('BLZ_adm1.shp') as src:
    # Preallocate array
    geom_np = np.zeros((500, 500, len(src)), dtype = np.int8)
    for id, geom in enumerate(src):
        geom_np[:,:,id] = features.rasterize([geom['geometry']], out_shape=(500,500), transform=Affine(0.01, 0.0, -90.0, 0, -0.01, 18.0))

If you have a 'matching' image you would probably use its shape and transform instead of those I arbitrarily defined in the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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