用python gdal包处理tif遥感图像

386 阅读3分钟

「这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战」。

用python gdal包处理tif遥感图像

先讲讲gdal包的安装,先前轻敌,以为pip就安装了,现在发现这是不可能的事情,只能用conda安装,也是这么久第一次遇到的。

1.gdal安装

conda install gdal

安装前,会自动下载安装一堆conda包

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    aws-c-common-0.4.57        |       ha925a31_1         147 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    aws-c-event-stream-0.1.6   |       hd77b12b_5          26 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    aws-checksums-0.1.9        |       ha925a31_0          50 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    aws-sdk-cpp-1.8.185        |       hd77b12b_0         2.5 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    blas-1.0                   |              mkl           6 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    bzip2-1.0.8                |       he774522_0         113 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    ca-certificates-2021.10.26 |       haa95532_2         115 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    certifi-2021.10.8          |   py37haa95532_2         152 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    cfitsio-3.470              |       he774522_6         512 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    curl-7.80.0                |       h2bbff1b_0         137 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    expat-2.4.1                |       h6c2663c_2         201 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    freexl-1.0.6               |       h2bbff1b_0          51 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    gdal-3.0.2                 |   py37hb978731_1         1.0 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    geos-3.8.0                 |       h33f27b4_0         905 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    geotiff-1.6.0              |       h5770a2b_0         128 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    hdf4-4.2.13                |       h712560f_2         1.3 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    hdf5-1.10.6                |       h7ebc959_0         7.9 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    icc_rt-2019.0.0            |       h0cc432a_1         6.0 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    intel-openmp-2021.4.0      |    haa95532_3556         2.2 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    jpeg-9d                    |       h2bbff1b_0         283 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    kealib-1.4.14              |       hde4a422_1         140 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    krb5-1.19.2                |       h5b6d351_0         697 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libcurl-7.80.0             |       h86230a5_0         295 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libgdal-3.0.2              |       ha1b3edf_1         7.0 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libiconv-1.15              |       h1df5818_7         626 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libnetcdf-4.6.1            |       hf59b723_4         501 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libpng-1.6.37              |       h2a8f88b_0         333 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libpq-12.9                 |       hb652d5d_1         2.7 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libspatialite-4.3.0a       |       h7ffb84d_0         2.3 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libssh2-1.9.0              |       h7a1dbc1_1         215 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libtiff-4.2.0              |       hd0e1b90_0         786 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    libxml2-2.9.12             |       h0ad7f3c_0         1.5 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    lz4-c-1.9.3                |       h2bbff1b_1         132 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    m2w64-expat-2.1.1          |                2         160 KB
    m2w64-gcc-libgfortran-5.3.0|                6         340 KB
    m2w64-gcc-libs-5.3.0       |                7         518 KB
    m2w64-gcc-libs-core-5.3.0  |                7         213 KB
    m2w64-gettext-0.19.7       |                2         4.2 MB
    m2w64-gmp-6.1.0            |                2         689 KB
    m2w64-libiconv-1.14        |                6         1.5 MB
    m2w64-libwinpthread-git-5.0.0.4634.697f757|                2          30 KB
    m2w64-xz-5.2.2             |                2         395 KB
    mkl-2021.4.0               |     haa95532_640       114.9 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    mkl-service-2.4.0          |   py37h2bbff1b_0          49 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    mkl_fft-1.3.1              |   py37h277e83a_0         135 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    mkl_random-1.2.2           |   py37hf11a4ad_0         216 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    msys2-conda-epoch-20160418 |                1           2 KB
    numpy-1.21.2               |   py37hfca59bb_0          24 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    numpy-base-1.21.2          |   py37h0829f74_0         4.4 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    openjpeg-2.4.0             |       h4fc8c34_0         219 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    openssl-1.1.1m             |       h2bbff1b_0         4.8 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    postgresql-12.9            |       hb652d5d_1        13.5 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    proj-6.2.1                 |       h9f7ef89_0         7.9 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    six-1.16.0                 |     pyhd3eb1b0_0          18 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    tiledb-2.2.9               |       hf7ce2e6_0         948 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    xerces-c-3.2.3             |       ha925a31_0         2.8 MB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    xz-5.2.5                   |       h62dcd97_0         244 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    zlib-1.2.11                |       h8cc25b3_4         112 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    zstd-1.4.9                 |       h19a0ad4_0         478 KB  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main

2.编写tif2jpg函数


#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:livingbody
@file:tif2jpg.py
@time:2022/01/21
"""
import cv2
import numpy as np
from osgeo import gdal


def tif2jpg(tif_path, lower_percent=0.6, higher_percent=99.4):
    ds = gdal.Open(tif_path, gdal.GA_ReadOnly)
    origin_label = np.empty(shape=(ds.RasterYSize, ds.RasterXSize, ds.RasterCount),
                            dtype='float64')
    for i in range(ds.RasterCount):
        band = ds.GetRasterBand(ds.RasterCount - i)
        origin_label[:, :, i] = band.ReadAsArray()
    label = np.zeros_like(origin_label, dtype='uint8')
    for i in range(origin_label.shape[2]):
        l, h = 0, 255
        l_cut, h_cut = np.percentile(origin_label[:, :, i], lower_percent), \
                       np.percentile(origin_label[:, :, i], higher_percent)
        channel = l + (origin_label[:, :, i] - l_cut) * (h - l) / (h_cut - l_cut)
        channel[channel < l] = l
        channel[channel > h] = h
        label[:, :, i] = channel
    return label


if __name__ == '__main__':
    cv2.imwrite('1.jpg', tif2jpg('000025_GF.tif'))

3.gdal库引入及使用效果

from osgeo import gdal如果正常结束,就没有问题了。

下载.png

3.AI Studio中gdal库的安装和使用

  1. 用AI Studio基础版环境,不要用至尊版,会出很奇怪的问题;
  2. 用conda安装,不要用pip;
  3. 安装到/home/aistudio/文件夹下,利用AI Studio的文件保存,避免每次都重新安装GDAL,安装挺耗时的,大概7分钟;
  4. 安装命令带上-y参数,避免安装过程中需要交互,导致安装被阻塞。

具体安装如下:

# 安装
!mkdir /home/aistudio/extlib !conda install --prefix=/home/aistudio/extlib gdal -y

# 引入
import sys sys.path.append('/home/aistudio/extlib/lib/python3.6/site-packages')

4.gdal库引入及使用效果

生成tif图

import matplotlib.pyplot as plt 
import numpy as np 
%matplotlib inline 
driver = gdal.GetDriverByName("GTiff") 
data = driver.Create("1.tif", xsize=300,ysize=200,bands=3) data.FlushCache() 
data = None 
img = plt.imread("1.tif") 
plt.imshow(img)

生成tif图

import numpy as np 
import matplotlib.pyplot as plt 
driver = gdal.GetDriverByName("GTiff") 
data = driver.Create("1.tif", ysize=200,xsize=300,bands=3) 
for i in range(3):
    outband=data.GetRasterBand(i+1) 
    in_array = np.random.rand(200,300)*255 
    outband.WriteArray(in_array.astype(int)) 
data.FlushCache() 
data = None 
img = plt.imread("1.tif") 
plt.imshow(img)