Python遥感图像处理指南(6)-绘制散点图和输出PDF报告

        今天我们来学习一些其他技能,在写论文时通常需要将结果图表进行整理,拼接图片很不方便,我们可以借助Pyhton将处理的图片和图标整合到PDF中输出,提高生产效率。

1、环境安装

安装PyPDF2 包

pip install PyPDF2

2、创建PDF

        我们将改造之前写的load_landsat_image 方法,来实现PDF文件的创建。整个图像对于 PDF 文件来说太大,为了保持长宽比不变,我们将只接收宽度作为参数,然后计算相应的高度,并将其传递给 rasterio 的读取函数,使用 create_rgb 函数创建 RGB 图像。请注意,我们会剪切大于 1 的值,因为我们需要 [0...1] 之间的值,以避免之后创建 PDF 时出现问题。创建 RGB 图像后,我们将不使用 plt.imshow 显示图像,而是直接使用 plt.imsave 将其保存为 .PDF 文件。

import rasterio
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np

def load_landsat_image(img_folder, bands, width=None):
    # initialize the dictionaries
    image = {}
    ds = {}
    
    path = Path(img_folder)
    
    # adjust the out_shape
    if width is not None:
        out_shape = (int(width/7601 * 7761), width)
        print(f'Using output shape ({out_shape})')
    else:
        out_shape = None
    
    # loop through the given bands to load
    for band in bands:
        # considering the landsat images end with *_SR_B#.TIF, we will use it to locate the correct file
        file = next(path.glob(f'*{band}.tif'))
        print(f'Opening file {file}')
        ds.update({band: rasterio.open(file)})
        image.update({band: ds[band].read(1, out_shape=out_shape)})

    return image, ds

def create_rgb(img, b_r, b_g, b_b, alpha=1.):
    rgb = np.stack([img[b_r], img[b_g], img[b_b]], axis=-1)
    rgb = rgb/rgb.max() * alpha
    
    # clip values outside the boundaries
    rgb[rgb>1] = 1
    rgb[rgb<0] = 0
    
    return rgb
    
# load the image
img, image_ds = load_landsat_image('D:/Images/Input/Landsat/LC08_L2SP_231062_20201026_20201106_02_T1/', 
                                   ['B2', 'B3', 'B4', 'B5', 'QA_PIXEL'], 
                                   width=1000)

# create the RGB for the image
rgb = create_rgb(img, 'B4', 'B3', 'B2', alpha=2.)

plt.imsave('d:/temp/rgb.pdf', rgb)

3、创建包含掩膜图像的PDF

        在前面几章的学习中我们已经学到了云、阴影、水体的掩膜生产方法,现在将他们输出到PDF中

L8_flags = {
    'dilated_cloud': 1<<1,
    

你可能感兴趣的:(Python数据处理,python)