【PythonRS】Pyrsgis库安装+基础函数使用教程

        pyrsgis库是一个用于处理地理信息系统(GIS)数据的Python库。它提供了一组功能强大的工具,可以帮助开发人员使用Python语言创建、处理、分析和可视化GIS数据。通过使用pyrsgis库,开发人员可以更轻松地理解和利用地理信息。

        pyrsgis库包含了许多常见的GIS操作和功能,例如读取和写入shapefile文件、转换坐标系、执行空间查询、计算地理特征属性等。它提供了许多方便使用的类和方法,例如GeoPandas、Shapely、Fiona、Rasterio、Pyproj和GDAL等,这些都可以帮助开发人员更高效地处理GIS数据。

一、Pyrsgis库安装

        Pyrsgis可以直接通过pip install pyrsgis安装,同样也可以下载压缩包然后本地安装。PyPI中Pyrsgis包下载地址:pyrsgis · PyPI

二、导入库和函数

        这些都是我后面代码需要使用到的函数,注意要导入,别到时候报错。

import os
from pyrsgis import raster, convert, ml

三、基础操作代码展示

1)获取影像基本信息

def Get_data(filepath):# 获取影像基本信息ds, data_arr = raster.read(filepath)  # 基础信息资源和数组ds_bands = ds.RasterCount  # 波段数ds_width = ds.RasterXSize  # 宽度ds_height = ds.RasterYSize  # 高度ds_bounds = ds.bbox  # 四至范围ds_geo = ds.GeoTransform  # 仿射地理变换参数ds_prj = ds.Projection  # 投影坐标系print("影像的宽度为:" + str(ds_width))print("影像的高度为:" + str(ds_height))print("仿射地理变换参数为:" + str(ds_geo))print("投影坐标系为:" + str(ds_prj))

2)计算NDVI

        这里给大家介绍一个经典案例,就是NDVI的计算。通过这个应该很容易就能理解Pyrsgis库的数据结构了。

def Get_NDVI(filepath):# 计算NDVIds, data_arr = raster.read(filepath)red_arr = data_arr[3, :, :]nir_arr = data_arr[4, :, :]result_arr = (nir_arr - red_arr) / (nir_arr + red_arr)# result_arr = (data_arr[4, :, :] - data_arr[3, :, :]) / (data_arr[4, :, :] + data_arr[3, :, :])output_file = r'E:/path_to_your_file/landsat8_result.tif'raster.export(result_arr, ds, output_file, dtype='float32', bands="all", nodata=0, compress="LZW")# 写入的数组,基础信息,路径,格式,波段,无效值,压缩方式

3)空间位置裁剪

        这里的裁剪主要是按照输入的空间矩形进行裁剪,并没有演示如何使用shp进行裁剪。这个可以应用于分幅裁剪、滑动裁剪等。空行分割的是实现这个功能的两种函数的使用方式。

def Clip_data(filepath):# 按掩膜提取ds, data_arr = raster.read(filepath)print('Original bounding box:', ds.bbox)print('Original shape of raster:', data_arr.shape)new_ds, clipped_arr = raster.clip(ds, data_arr, x_min=770000, x_max=790000, y_min=1420000, y_max=1440000)raster.export(clipped_arr, new_ds, r'E:/path_to_your_file/clipped_file.tif')infile = r'E:/path_to_your_file/your_file.tif'outfile = r'E:/path_to_your_file/clipped_file.tif'raster.clip_file(infile, x_min=770000, x_max=790000, y_min=1420000, y_max=1440000, outfile=outfile)

4)移除无效值

        这里的函数是移除无效值的,如-9999之类的,理论上应该也可以修改其他的DN值,但我自己没去试过,大家可以自行尝试。

def Modify_data(filepath):# 修改影像数组,如移除无效值ds, data_arr = raster.read(filepath)new_ds, new_arr = raster.trim(ds, data_arr, remove=-9999)print('Shape of the input array:', data_arr.shape)print('Shape of the trimmed array:', new_arr.shape)ds, data_arr = raster.read(filepath)new_arr = raster.trim_array(data_arr, remove=-9999)print('Shape of the input array:', data_arr.shape)print('Shape of the trimmed array:', new_arr.shape)infile = r'E:/path_to_your_file/your_file.tif'outfile = r'E:/path_to_your_file/trimmed_file.tif'raster.trim_file(infile, -9999, outfile)

5)平移影像

        按照x、y方向进行影像平移,可选像素和坐标进行平移。

def Shift_data(filepath):# 平移影像ds, data_arr = raster.read(filepath)new_ds = raster.shift(ds, x=10, y=10)  # x,y方向偏移量。按栅格的投影单位移动数据源 或分别按细胞数print('Original bounding box:', ds.bbox)print('Modified bounding box:', new_ds.bbox)new_ds = raster.shift(ds, x=10, y=10, shift_type='cell')  # shift_type='coordinate'print('Modified bounding box:', new_ds.GeoTransform)raster.export(data_arr, new_ds, r'E:/path_to_your_file/shifted_file.tif')infile = r'E:/path_to_your_file/your_file.tif'outfile = r'E:/path_to_your_file/shifted_file.tif'raster.shift_file(infile, x=10, y=10, outfile=outfile, shift_type='cell')

6)数组、表、CSV互转(包含剔除值)

        这里的函数是数组、表、CSV互转,在转换的同时可以通过参数移除某些DN值。

def Convert_data(filepath):# 数组转表、CSV,修改值input_file = r'E:/path_to_your_file/raster_file.tif'ds, data_arr = raster.read(input_file)  # Shape of the input array: (6, 800, 400)data_table = convert.array_to_table(data_arr)  # Shape of the reshaped array: (320000, 6)# 该函数将单波段或多波段栅格数组转换为表,其中 列表示输入波段,每行表示一个单元格。input_file = r'E:/path_to_your_file/raster_file.tif'ds, data_arr = raster.read(input_file)data_table = convert.array_to_table(data_arr)print('Shape of the input array:', data_arr.shape)  # Shape of the input array: (6, 800, 400)print('Shape of the reshaped array:', data_table.shape)  # Shape of the reshaped array: (320000, 6)input_file = r'E:/path_to_your_file/raster_file.tif'new_data_arr = convert.table_to_array(data_table, n_rows=ds.RasterYSize, n_cols=ds.RasterXSize)print('Shape of the array with newly added bands:', new_data_arr.shape)# Shape of the array with newly added bands: (8, 800, 400)new_data_arr = convert.table_to_array(data_table[:, -2:], n_rows=ds.RasterYSize, n_cols=ds.RasterXSize)print('Shape of the array with newly added bands:', new_data_arr.shape)# Shape of the array with newly added bands: (2, 800, 400)# 表转数组input_file = r'E:/path_to_your_file/raster_file.tif'output_file = r'E:/path_to_your_file/tabular_file.csv'convert.raster_to_csv(input_file, filename=output_file)input_dir = r'E:/path_to_your_file/'output_file = r'E:/path_to_your_file/tabular_file.csv'convert.raster_to_csv(input_dir, filename=output_file)convert.raster_to_csv(input_dir, filename=output_file, negative=False, remove=[10, 54, 127], badrows=False)# 数组转表,可剔除负值、目标值、坏波段input_file = r'E:/path_to_your_file/raster_file.tif'out_csvfile = input_file.replace('.tif', '.csv')convert.raster_to_csv(input_file, filename=out_csvfile, negative=False)new_csvfile = r'E:/path_to_your_file/predicted_file.tif'out_tiffile = new_csvfile.replace('.csv', '.tif')convert.csv_to_raster(new_csvfile, ref_raster=input_file, filename=out_tiffile, compress='DEFLATE')convert.csv_to_raster(new_csvfile, ref_raster=input_file, filename=out_tiffile,cols=['Blue', 'Green', 'KMeans', 'RF_Class'], compress='DEFLATE')# 数组将堆叠并导出为多光谱文件convert.csv_to_raster(new_csvfile, ref_raster=input_file, filename=out_tiffile,cols=['Blue', 'Green', 'KMeans', 'RF_Class'], stacked=False, compress='DEFLATE')# 将每列导出为单独的波段,请将参数设置为 。stacked=False

7)制作深度学习标签

        此函数根据单波段或多波段栅格阵列生成影像片。图像芯片可以用作深度学习模型的直接输入(例如。卷积神经网络),输出格式:(4198376, 7, 7, 6)

def Create_CNN(filepath):# 此函数根据单波段或多波段栅格阵列生成影像片。图像 芯片可以用作深度学习模型的直接输入(例如。卷积神经网络)# -----------------------------数组生成深度学习芯片-----------------------------infile = r'E:/path_to_your_file/your_file.tif'ds, data_arr = raster.read(infile)image_chips = ml.array_to_chips(data_arr, y_size=7, x_size=7)print('Shape of input array:', data_arr.shape)  # Shape of input array: (6, 2054, 2044)print('Shape of generated image chips:', image_chips.shape)  # Shape of generated image chips: (4198376, 7, 7, 6)infile = r'E:/path_to_your_file/your_file.tif'ds, data_arr = raster.read(infile)image_chips = ml.array2d_to_chips(data_arr, y_size=5, x_size=5)print('Shape of input array:', data_arr.shape)  # Shape of input array: (2054, 2044)print('Shape of generated image chips:', image_chips.shape)  # Shape of generated image chips: (4198376, 5, 5)# ----------------------------影像直接生成深度学习芯片----------------------------infile_2d = r'E:/path_to_your_file/your_2d_file.tif'image_chips = ml.raster_to_chips(infile_2d, y_size=7, x_size=7)print('Shape of single band generated image chips:', image_chips.shape)# Shape of single bandgenerated image chips: (4198376, 7, 7)infile_3d = r'E:/path_to_your_file/your_3d_file.tif'image_chips = ml.raster_to_chips(infile_3d, y_size=7, x_size=7)print('Shape of multiband generated image chips:', image_chips.shape)# Shape of multiband generated image chips: (4198376, 7, 7, 6)

8)翻转影像

        按照东西或南北方向翻转影像

def Reverse_Image(filepath):# 按照东西、南北方向反转影像# -------------------------------北向、东向翻转--------------------------------input_file = r'E:/path_to_your_file/your_file.tif'ds, data_arr = raster.read(input_file)north_arr, east_arr = raster.north_east(data_arr)print(north_arr.shape, east_arr.shape)north_arr, east_arr = raster.north_east(data_arr, flip_north=True, flip_east=True)north_arr = raster.north_east(data_arr, layer='north')from matplotlib import pyplot as pltplt.imshow(north_arr)plt.show()plt.imshow(east_arr)plt.show()input_file = r'E:/path_to_your_file/your_file.tif'ds, data_arr = raster.read(input_file)north_arr, east_arr = raster.north_east(data_arr)print(north_arr.shape, east_arr.shape)north_arr = raster.north_east(data_arr, layer='north')from matplotlib import pyplot as pltplt.imshow(north_arr)plt.show()plt.imshow(east_arr)plt.show()raster.export(north_arr, ds, r'E:/path_to_your_file/northing.tif', dtype='float32')raster.export(east_arr, ds, r'E:/path_to_your_file/easting.tif', dtype='float32')# -------------------------使用参考.tif文件生成北向栅格----------------------------reference_file = r'E:/path_to_your_file/your_file.tif'raster.northing(file1, r'E:/path_to_your_file/northing_number.tif', flip=False, value='number')raster.northing(file1, r'E:/path_to_your_file/northing_normalised.tif', value='normalised')  # 输出栅格进行归一化raster.northing(file1, r'E:/path_to_your_file/northing_coordinates.tif', value='coordinates')raster.northing(file1, r'E:/path_to_your_file/northing_number_compressed.tif', compress='DEFLATE')reference_file = r'E:/path_to_your_file/your_file.tif'raster.easting(file1, r'E:/path_to_your_file/easting_number.tif', flip=False, value='number')raster.easting(file1, r'E:/path_to_your_file/easting_normalised.tif', value='normalised')raster.easting(file1, r'E:/path_to_your_file/easting_normalised.tif', value='normalised')raster.easting(file1, r'E:/path_to_your_file/easting_number_compressed.tif', compress='DEFLATE')

四、总结

        Pyrsgis库之前使用的时候是因为要进行卷积神经网络的深度学习,然后里面制作深度学习标签的函数还是不错的,可以用一行代码实现标签的制作。但是如果数据过大,内存就会溢出报错,这个是Pyrsgis库没有解决的,当然我也没解决=。=大家可以自己尝试一下,有解决办法可以和我分享一下。总的来说Pyrsgis和Rasterio这两个库都还不错,都在GDAL的基础上进行了二开,方便了很多操作。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/121853.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Git: 仓库clone和用户配置

git clone 两种方式clone远程仓库到本地。 通过ssh 命令格式: git clone gitxxxxxx.git使用这种方法需要提前创建ssh秘钥。 首先打开一个git控制台,输入命令 ssh-keygen -t ed25519 -C “xxxxxxxxxx.com”输入命令后需要点击四次回车,其…

mysql 计算两个坐标距离

方式一:st_distance_sphere 计算结果单位米 SELECT *, st_distance_sphere(point(lng,lat),point(lng,lat)) as distance FROM table mysql 版本5.7 以上 方式二:st_distance 计算结果单位是度 SELECT *, (st_distance(point(lng,lat),point(lng4,lat…

自学SLAM(5)《第三讲:李群和李代数》作业

前言 小编研究生的研究方向是视觉SLAM,目前在自学,本篇文章为初学高翔老师课的第三次作业。 文章目录 前言1.群的性质2.验证向量叉乘的李代数性质3.推导 SE(3) 的指数映射4.伴随5.轨迹的描绘6.* 轨迹的误差(附加题) 1.群的性质 课上我们讲解了什么是群。…

Spring Security—Spring MVC 整合

目录 一、EnableWebMvcSecurity 二、MvcRequestMatcher 三、AuthenticationPrincipal 四、异步 Spring MVC 整合 五、Spring MVC 和 CSRF 整合 1、自动包含 Token 2、解析 CsrfToken Spring Security提供了一些与Spring MVC的可选整合。本节将进一步详细介绍这种整合。 …

UML中类之间的六种主要关系

UML中类之间的六种主要关系: 继承(泛化)(Inheritance、Generalization), 实现(Realization),关联(Association),聚合(Aggregation),组…

Linux--进程替换

1.什么是进程替换 在fork函数之后,父子进程各自执行代码的一部分,但是如果子进程想要执行一份全新的程序呢? 通过进程替换来完成,进程替换就是父子进程代码发生写时拷贝,子进程执行自己的功能。 程序替换就是通过特定的…

python 笔记:h5py 读取HDF5文件

1 HDF5文件 HDF5 是 Hierarchical Data Format version 5 的缩写,是一种用于存储和管理大量数据的文件格式一个h5py文件可以看作是 “dataset” 和 “group” 二合一的容器 dataset : 数据集,像 numpy 数组一样工作group : 包含了其它 dataset 和 其它 …

GZ035 5G组网与运维赛题第4套

2023年全国职业院校技能大赛 GZ035 5G组网与运维赛项(高职组) 赛题第4套 一、竞赛须知 1.竞赛内容分布 竞赛模块1--5G公共网络规划部署与开通(35分) 子任务1:5G公共网络部署与调试(15分) 子…

C语言_断言assert详解

一、assert定义 assert() 的用法像是一种"契约式编程",在我的理解中,其表达的意思就是,程序在我的假设条件下,能够正常良好的运作,其实就相当于一个 if 语句: if(假设成立) {程序正常运行&…

(免费领源码) Asp.Net#SQL Server校园在线投票系统10557-计算机毕业设计项目选题推荐

摘 要 随着互联网大趋势的到来,社会的方方面面,各行各业都在考虑利用互联网作为媒介将自己的信息更及时有效地推广出去,而其中最好的方式就是建立网络管理系统,并对其进行信息管理。由于现在网络的发达,校园投票通过网…

java - IDEA IDE - 设置字符串断点

文章目录 java - IDEA IDE - 设置字符串断点概述笔记END java - IDEA IDE - 设置字符串断点 概述 IDE环境为IDEA2022.3 在看一段序列化的代码, 想找出报错抛异常那个点, 理解一下代码实现. 因为序列化代码实现在第三方jar包中, 改不了(只读的). 根本数不清第几次才会开始报…

java基础之泛型

泛型 泛型是在JDK1.5增加的功能,在没有泛型之前,从集合中取出来的每一个对象都必须进行强制类型转换,如果有人插入了错误类型的对象,在运行时的转换就会出现问题,有了泛型之后,这些问题就会在编译期暴露出来…

OpenCV学习(五)——图像基本操作(访问图像像素值、图像属性、感兴趣区域ROI和图像边框)

图像基本操作 5. 图像基本操作5.1 访问像素值并修改5.2 访问图像属性5.2 图像感兴趣区域ROI5.3 拆分和合并图像通道5.4 为图像设置边框(填充) 5. 图像基本操作 访问像素值并修改访问图像属性设置感兴趣区域(ROI)分割和合并图像 …

如何在vscode中添加less插件

Less (Leaner Style Sheets 的缩写) 是一门向后兼容的 CSS 扩展语言。它对CSS 语言增加了少许方便的扩展,通过less可以编写更少的代码实现更强大的样式。但less不是css,浏览器不能直接识别,即浏览器无法执行less代码&a…

2023年正版win10/win11系统安装教学(纯净版)

第一步:准备一个8G容量以上的U盘。 注意,在制作系统盘时会格式化U盘,所以最好准备个空U盘,防止资料丢失。 第二步:制作系统盘。 安装win10 进入windows官网 官网win10下载地址:https://www.microsoft.c…

安卓开发实例:随机数

点击按钮生成一个1-100之间的随机数 activity_random_number.xml <?xml version"1.0" encoding"utf-8"?> <androidx.constraintlayout.widget.ConstraintLayoutxmlns:android"http://schemas.android.com/apk/res/android"xmlns:a…

conda 复制系统环境

直接复制 想要通过 conda 直接复制一个已存在的环境&#xff0c;你可以使用 conda create 命令并配合 --clone 参数。以下是具体步骤&#xff1a; 查看现有的环境: 首先&#xff0c;你可以使用以下命令来查看所有的 conda 环境&#xff1a; conda env list这会给你一个环境列表…

TypeScript -类型断言的简单理解

类型断言是干啥的 类型断言 &#xff1a; 是手动的给某个变量 指定类型&#xff0c;从而可以方便操作该类型的属性和方法。 类型断言的两种写法 方式一 &#xff1a; 变量名 as 类型 let x: number | string abc; console.log((x as string).length); // 输出 3 &#xff0c;因…

10月Java行情 回暖?

最近面试 Java 开发&#xff0c;看看行情。总的来说没有前几年好&#xff0c;真的是互联网寒冬&#xff0c;面试机会都比以前少了不少&#xff0c;很多互联网公司都在降本增效&#xff0c;只招少量的人。如果你能约到面试就好好珍惜&#xff0c;记住不要裸辞&#xff0c;不要裸…

记一次vue3实现TRSP大华相机拉流的经历

一、背景 业务场景&#xff0c;大华IP相机安装在A城市某建筑场所&#xff0c;工控机是内网通过4G流量卡上网&#xff0c;工控机通过相机采集数据后做故障识别并上传故障信息到地面服务器&#xff0c;地面服务器在B城市。 现需要在地面服务器提供的WEB界面上实现IP相机实时拉流…