python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python栅格化地图

利用Python栅格化地图(以成都市为例,含代码)

作者:数据的旅途

这篇文章主要给大家介绍了关于利用Python栅格化地图的相关资料,
Python中可以使用多种库来进行栅格化地图的操作,其中比较常用的有geopandas、rasterio等,文中通过代码介绍的非常详细,需要的朋友可以参考下

python代码实现

读取成都市边界的图层文件(.shp),并可视化

import geopandas as gpd

cd_shape = gpd.read_file('Chengdu/Chengdu.shp')
cd_shape.plot(edgecolor='k',facecolor='none')

下面这个栅格地图的类是我自己写的,类的参数主要有

class RasterData:

    def __init__(self, raster_data_path: str, length: float):
        self.raster = gpd.read_file(raster_data_path)
        self.length = length/1000 * 0.009
        self.polygons = []
        self.grid_ids = []
        self.x_min, self.y_min, self.x_max, self.y_max = self.raster.total_bounds
        self.rows, self.cols = self.grid_shape()

    def grid_shape(self) -> tuple:
        rows = int(math.ceil((self.y_max - self.y_min) / float(self.length)))
        cols = int(math.ceil((self.x_max - self.x_min) / float(self.length)))
        return rows, cols

    def grid_num(self) -> int:
        return self.rows * self.cols

    def grid_map(self) -> gpd.GeoDataFrame:
        points_list = []
        for row in range(self.rows):
            for col in range(self.cols):
                center_point_x = self.x_min + self.length / 2 + col * self.length
                center_point_y = self.y_min + self.length / 2 + row * self.length
                
                points = [Point(center_point_x + dx * self.length / 2,
                                center_point_y + dy * self.length / 2)
                          for dx, dy in [(-1, 1), (1, 1), (1, -1), (-1, -1)]]
                points_list.append(points)

        polygons = [Polygon(points) for points in points_list]
        grid_ids = list(range(len(polygons)))
        
        grid = gpd.GeoDataFrame({'geometry': polygons, 'grid_id': grid_ids}, crs=self.raster.crs)
        return grid
        
    # 计算栅格与区域的交集
    def grid_intersection(self, region: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
        grid = self.grid_map()
        intersection_data = gpd.overlay(grid, region, how='intersection')
        return intersection_data

实例化对象并调用grid_map方法

grid = RasterData('Chengdu/Chengdu.shp', 2000) # 实例化对象
grid_data = grid.grid_map() # 调用grid_map方法进行栅格化
# 将两个图层绘制在一起
fig, ax = plt.subplots(figsize=(10, 10))
# 加粗绘图的线宽
cd_shape.plot(ax=ax, edgecolor='k', linewidth=1, facecolor='none')
grid_data.plot(ax=ax, edgecolor='k', linewidth=0.5, facecolor='none')

得到栅格模型,但此时的栅格是根据成都市边界的最大范围进行划分的,很多时候我们需要的是地理边界内部的栅格,因此需要调用grid_intersection方法

# 将两个图层绘制在一起
fig, ax = plt.subplots(figsize=(10, 10))
# 加粗绘图的线宽
intersection_data = grid.grid_intersection(cd_shape)
cd_shape.plot(ax=ax, edgecolor='k', linewidth=1, facecolor='none')
intersection_data.plot(ax=ax, edgecolor='k', linewidth=0.5, facecolor='none')

最终就得到了栅格化后的数据,是DataFrame格式的,其中grid_id代表栅格编号,geometry代码当前栅格的多边形要素

总结 

到此这篇关于利用Python栅格化地图的文章就介绍到这了,更多相关Python栅格化地图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文