利用python进行矢量转栅格操作

利用python进行矢量转栅格操作

基于rasterio和geopandas两个库包对矢量进行栅格化操作

#!usr/bin/env python
# -*- coding: utf-8 -*-
"""
date:2021/7/8
author:甲戌_Tr
email: liu_xxxi@163.com
"""

import sys,os
import geopandas as gpd
import rasterio
from rasterio import features
from rasterio.crs import CRS
from rasterio.transform import Affine

class Polygon2Raster:
    def polygon_to_raster(self,shp,raster,pixel,field,code=4326):
        '''
        矢量转栅格
        :param shp: 输入矢量全路径,字符串,无默认值
        :param raster: 输出栅格全路径,字符串,无默认值
        :param pixel: 像元大小,与矢量坐标系相关
        :param field: 栅格像元值字段
        :param Code: 输出坐标系代码,默认为4326
        :return: None
        '''

        # 判断字段是否存在
        shapefile = gpd.read_file(shp)
        if not field in shapefile.columns:
            raise Exception ('输出字段不存在')
        # 判断数据类型
        f_type = shapefile.dtypes.get(field)
        if 'int' in str(f_type):
            shapefile[field] = shapefile[field].astype('int16')
            dtype = 'int16'
        elif 'float' in str(f_type):
            shapefile[field] = shapefile[field].astype('float32')
            dtype = 'float32'
        else:
            raise Exception ('输入字段数据类型为{},无法进行栅格化操作'.format(f_type))

        bound = shapefile.bounds
        width = int((bound.get('maxx').max()-bound.get('minx').min())/pixel)
        height = int((bound.get('maxy').max()-bound.get('miny').min())/pixel)
        transform = Affine(pixel, 0.0, bound.get('minx').min(),
               0.0, -pixel, bound.get('maxy').max())

        meta = {'driver': 'GTiff',
                'dtype': dtype,
                'nodata': 0,
                'width': width,
                'height': height,
                'count': 1,
                'crs': CRS.from_epsg(code),
                'transform': transform}

        with rasterio.open(raster, 'w+', **meta) as out:
            out_arr = out.read(1)
            shapes = ((geom,value) for geom, value in zip(shapefile.get('geometry'), shapefile.get(field)))
            burned = features.rasterize(shapes=shapes, fill=0, out=out_arr, transform=out.transform)
            out.write_band(1, burned)

if __name__ == '__main__':
    in_shp = r'test.shp'
    out_tif = r'test.tif'
    pixel_size = 0.01
    field = 'data'
    Polygon2Raster().polygon_to_raster(in_shp,out_tif,pixel_size,field)
    print('finish')

欢迎指正~

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值