Friday, April 13, 2018

[Python] read bil.zip file in python

The bil file is a widely-used GIS format, which can be read through gdal library in python.

GDAL installation
Although I have installed gdal in python before, recently I have a problem running gdal library in anaconda python. The error is gdal.so.20 does not exist. The work-around is as below from a stack exchange GIS forum:
In anaconda, uninstall the previous gdal library by
$ conda uninstall gdal
And then reinstall the libgdal before installing gdal
$ conda install libgdal
$ conda install gdal

Test if you can import the gdal library in python:
>> import gdal, gdalconst

Read zip file
Before reading the bil file, we need to use a package "vsizip" to unzip the zip-file. First, change the directory to the data folder, and then modify the filename with vsizip
>> os.chdir('path/to/file')
>> filename = '/vsizip/the_name_of_the_file.zip/the_name_of_the_file.bil'

This used to work but now it returns the error as:
Recode from CP437 to UTF-8 failed with the error: "Invalid argument"

The work-around is as below from github:
set the environmental variable
export CPL_ZIP_ENCODING=UTF-8

Read bil file
After successfully decode the zip file, one can read the file using the modified filename.

>> gdal.GetDriverByName('EHdr').Register()
>> img = gdal.Open(filename, gdalconst.GA_ReadOnly)
>> band = img.GetRasterBand(1)
>> data = band.ReadAsArray()


No comments:

Post a Comment