当前位置: 首页 > news >正文

ASCII 文件与 TIFF 文件互转(Python 实现)(2023/03/09)

ASCII 文件与 TIFF 文件互转(Python 实现)

文章目录

  • ASCII 文件与 TIFF 文件互转(Python 实现)
    • 1. 环境
      • 1.1 Linux
      • 1.2 Windows
    • 2. 代码

1. 环境

1.1 Linux

$ pip3 install --index-url https://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com rioxarray

1.2 Windows

  1. 在Archived: Python Extension Packages for Windows - Christoph Gohlke (uci.edu)库中下载对应 python 版本的 GDAL 与 Rasterio 离线包,以 python3.10 为例:
    1. https://download.lfd.uci.edu/pythonlibs/archived/GDAL-3.4.3-cp310-cp310-win_amd64.whl
    2. https://download.lfd.uci.edu/pythonlibs/archived/rasterio-1.2.10-cp310-cp310-win_amd64.whl
  2. 安装
$ pip3 install GDAL-3.4.3-cp310-cp310-win_amd64.whl$ pip3 install rasterio-1.2.10-cp310-cp310-win_amd64.whl$ pip3 install --index-url https://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com rioxarray

2. 代码

#!/usr/bin/python3
# -*- encoding: utf-8 -*-
"""
@File    :   gis_util.py
@Desc    :   GIS 文件格式转换工具
@Version :   v1.0
@Time    :   2023/02/23
@Author  :   xiaoQQya
@Contact :   xiaoQQya@126.com
"""
import numpy as np
import rioxarray
import xarray as xrdef ascii_to_tiff(asc_path: str, tif_path: str, tif_attrs: dict = {}) -> None:"""ASCII 文件转 TIFF 文件:param asc_path: ASCII 文件路径, 例如: ./test.asc:type asc_path: str:param tif_path: TIFF 文件输出路径, 例如: ./test.tif:type tif_path: str:param tif_attrs: TIFF 文件属性, 例如: {"unit": "m"}, defaults to {}:type tif_attrs: dict, optional"""# 获取 ASCII 文件前 6 行属性值attrs: dict = {}with open(asc_path, "r") as file:for _ in range(6):line: str = file.readline().strip().split(" ")attrs[line[0].lower()] = eval(line[-1])if "xllcenter" not in attrs.keys():attrs["xllcenter"] = attrs["xllcorner"] + 0.5 * attrs["cellsize"]attrs["yllcenter"] = attrs["yllcorner"] + 0.5 * attrs["cellsize"]# 计算每个点经纬度坐标longitudes = [attrs["xllcenter"] + i * attrs["cellsize"] for i in range(attrs["ncols"])]latitudes = [attrs["yllcenter"] + i * attrs["cellsize"] for i in range(attrs["nrows"])]latitudes.reverse()# 读取 ASCII 文件矩阵数值data = np.loadtxt(asc_path, skiprows=6)data[data == attrs["nodata_value"]] = np.nanda = xr.DataArray(data, coords=[latitudes, longitudes], dims=["y", "x"])# 设置 TIFF 文件属性值tif_attrs["NODATA_VALUE"] = attrs["nodata_value"]da.attrs = tif_attrs# 设置 TIFF 文件参考系信息rioxarray.raster_array.RasterArray(da)da.rio.write_crs("epsg:4326", inplace=True)da.rio.to_raster(tif_path)def tiff_to_ascii(tif_path: str, asc_path: str) -> None:"""TIFF 文件转 ASCII 文件:param tif_path: TIFF 文件路径, 例如: ./test.tif:type tif_path: str:param asc_path: ASCII 输出文件路径, 例如: ./test.asc:type asc_path: str"""# 读取 TIFF 文件tif = rioxarray.open_rasterio(tif_path)shape = tif.rio.shapetransform = tif.rio.transform()# 获取 ASCII 文件前 6 行属性attrs: dict = {}attrs["ncols"] = shape[1]attrs["nrows"] = shape[0]attrs["xllcorner"] = transform[2]attrs["yllcorner"] = transform[5] + shape[0] * transform[4]attrs["cellsize"] = transform[0]attrs["nodata_value"] = tif.rio.nodata if tif.rio.nodata else -9999# 获取数据data = tif.values[0]data[np.isnan(data)] = attrs["nodata_value"]# 写入文件with open(asc_path, "w") as file:for key, value in attrs.items():file.write(f"{key.upper():14}{value}\n")np.savetxt(fname=file, X=data, fmt="%.2f")if __name__ == "__main__":ascii_to_tiff("./ascs/dem.asc", "./tifs/dem.tif", {"UNIT": "m"})tiff_to_ascii("./tifs/dem.tif", "./ascs/dem2.asc")

注意:ASCII 文件与 TIFF 文件除了存在格式差异,还存在元空间表达方式的差异。ASCII 文件坐标值在像元的左下角,而 TIFF 文件坐标值在像元的左上角,因此在格式转换时需要注意坐标转换问题。

参考资料:

  • 使用python转换netCDF与GeoTIFF格式_沉研的博客-CSDN博客
  • Getting Started — rioxarray 0.13.3 documentation (corteva.github.io)
  • 学习笔记 | Python处理矢栅数据(1)_open_rasterio翻转_GeoSuper的博客-CSDN博客
  • 学习笔记 | Python处理矢栅数据(2)_python处理 osgb_GeoSuper的博客-CSDN博客
  • 利用Python+GDAL的脚本模式实现的一些基础gis功能集合_前端hsp矢量数据_一指流沙叹风华的博客-CSDN博客
http://www.lryc.cn/news/36605.html

相关文章:

  • 思科模拟器 | 交换机与路由器的配置汇总【收藏备用】
  • 电子台账:软件运行环境要求与功能特点
  • 计算机科学导论笔记(六)
  • 嵌入式从业10年,聊聊我对工业互联网和消费物联网的看法 | 文末赠书4本
  • python的django框架从入门到熟练【保姆式教学】第一篇
  • 浏览记录或者购物车的去重处理
  • Ubantu docker学习笔记(二)拉取构建,属于你的容器
  • 指针数组 数组指针 常量指针 指针常量 函数指针 指针函数
  • 前端js学习
  • “华为杯”研究生数学建模竞赛2007年-【华为杯】A题:食品卫生安全保障体系数学模型及改进模型(附获奖论文)
  • 转战C#---day2
  • 【vue2源码学习】— diff
  • 更换 Linux 自带的 jdk 环境
  • MySQL8读写分离集群
  • 蓝桥冲刺31天之第七天
  • 【Python百日进阶-Web开发-Vue3】Day550 - Vue3 商城后台 10:Veux4-02基本使用
  • ESP32驱动-红外寻迹传感器驱动
  • 【TS】TypeScript泛型 T 的用法详解
  • Vue 3.0 单文件组件 【Vue3 从零开始】
  • 北邮22信通:你是不是在looking for……那串代码?(2)第三章单链表
  • 蓝库云|告诉你传统产业该如何进行数字化转型
  • 121.(leaflet篇)leaflet结合echarts4迁徙图
  • 链表及其基本操作
  • 【Java基础 下】 031 -- 反射 动态代理
  • springcloud3 GateWay
  • 万字长文:Stable Diffusion 保姆级教程
  • WAMP搭建靶场
  • Uipath Excel 自动化系列13-ForEachExcelSheet(遍历Sheet)
  • JDBC快速入门
  • 蓝桥杯三月刷题 第六天