forked from robintw/GDALUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_io.py
48 lines (30 loc) · 1.18 KB
/
image_io.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import numpy as np
import pandas as pd
import gdal
def image_to_df(filename, bands, nodata=-9999):
"""Reads the specified bands from the specified image and imports
them to a pandas data frame.
Parameters:
* filename: Image filename to read (must be a GDAL-supported format) bands:
* A list of bands to process. Band IDs are 1-based. For example [1, 2, 3]
* for a standard Landsat image will process the Blue, Green and Red bands
* nodata: A No Data value to ignore, defaults to -9999
Returns: A pandas data frame with a column per band read, with all the data
in it, with no data values removed. Columns will be named "Bx" where x is
the band ID.
"""
im = gdal.Open(filename)
data = {}
for band_id in bands:
band = im.GetRasterBand(band_id).ReadAsArray().astype(float)
band[band == nodata] = np.nan
data['B%d' % band_id] = band.ravel()
df = pd.DataFrame(data)
df.dropna()
return df
def singleband_image_to_array(filename):
return image_to_array(filename, 1)
def image_to_array(filename, band=1):
img = gdal.Open(filename)
arr = img.GetRasterBand(band).ReadAsArray()
return arr