编程_栅格进行裁剪

需求

现在有一份SHP文件,需要把这份矢量文件制作为深度学习的标签。这时候第一个步骤是:把矢量栅格化。

代码

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
# @Time : 2023/11/27 10:18 
# @File : shp_clip_img.py

from osgeo import gdal
import os

#  根据shp 裁剪影像
def clip_image_by_shp(input_file, output_file, clip_shape, nodata=0):
    '''
    @todo 根据shp 裁剪影像
    @param shp_file: shp file
    @param img_file: image file
    @param outpath: output path
    @return:
    '''
    outpath = os.path.dirname(output_file)
    if os.path.exists(outpath):
        pass
    else:
        os.makedirs(outpath)
    # 根据已知矩形矢量裁剪图像
    input_file_raster = gdal.Open(input_file)  # 打开待裁剪图像
    # 用gdal.Warp裁剪,cropToCutline=True即使裁剪后的图像size和矢量一致,否则还和原图像一样。
    gdal.Warp(output_file,
                  input_file_raster,
                  format='GTiff',
                  cutlineDSName=clip_shape,
                  cropToCutline=True,
                  dstNodata=nodata)

if __name__ == '__main__':
    shp_file = r'D:\scope.shp'
    img_file = r'D:\img1.tif'
    outfile = r'D:\' + os.path.splitext(os.path.basename(img_file))[0]+ '.tif'
    clip_image_by_shp(img_file,outfile,shp_file)

代码解析

# 1.打开待裁剪图像
# 2.用gdal.Warp裁剪,cropToCutline=True即使裁剪后的图像size和矢量一致,否则还和原图像一样。
# 3.输出裁剪后的图像

image-20231201134942928

image-20231201135006382