生成一段python代码实现gdal转array
时间: 2023-12-02 13:02:21 浏览: 35
好的,以下是Python代码实现gdal转array的示例:
```
import gdal
import numpy as np
# 打开栅格数据
raster_dataset = gdal.Open('path_to_raster')
# 获取栅格数据的宽度和高度
cols = raster_dataset.RasterXSize
rows = raster_dataset.RasterYSize
# 获取栅格数据的通道数
bands = raster_dataset.RasterCount
# 读取栅格数据为数组
arr = []
for i in range(1, bands+1):
band = raster_dataset.GetRasterBand(i)
arr.append(band.ReadAsArray())
# 将数组堆叠成多维数组
stacked_arr = np.dstack(tuple(arr))
# 打印多维数组的形状
print(stacked_arr.shape)
```
希望以上代码对你有帮助!如果还有其他问题,欢迎随时提出。
相关问题
生成一段使用gdal批量将tif格式转换成png格式的带有注释的python代码
Sure, here's a Python code snippet that uses the GDAL library to batch convert TIFF files to PNG format:
```python
import os
from osgeo import gdal
# Set input and output directories
input_dir = '/path/to/tif/files'
output_dir = '/path/to/png/files'
# Loop through each file in input directory
for filename in os.listdir(input_dir):
if filename.endswith('.tif'):
# Open TIFF file
tif_file = gdal.Open(os.path.join(input_dir, filename))
# Set output file name
png_file = os.path.splitext(filename)[0] + '.png'
output_path = os.path.join(output_dir, png_file)
# Convert TIFF to PNG
gdal.Translate(output_path, tif_file, format='PNG')
# Add comment to output file
with open(output_path, 'a') as f:
f.write('# Converted from TIFF using GDAL')
print('Conversion complete')
```
Hope this helps! Let me know if you have any other questions.
用python写一段矢量转栅格的代码
好的,下面是一段用Python实现矢量转栅格的代码,基于GDAL库:
```python
import gdal
import numpy as np
# 打开矢量文件
src_ds = gdal.Open('vector.shp')
# 获取矢量文件范围、分辨率和投影
xmin, xres, xskew, ymax, yskew, yres = src_ds.GetGeoTransform()
xsize = src_ds.RasterXSize
ysize = src_ds.RasterYSize
proj = src_ds.GetProjection()
# 创建栅格数据集
dst_ds = gdal.GetDriverByName('GTiff').Create('raster.tif', xsize, ysize, 1, gdal.GDT_Byte)
# 设置栅格数据集的范围、分辨率和投影
dst_ds.SetGeoTransform((xmin, xres, xskew, ymax, yskew, yres))
dst_ds.SetProjection(proj)
# 将矢量文件转换为栅格数据
gdal.RasterizeLayer(dst_ds, [1], src_ds.GetLayer(), burn_values=[255])
# 读取栅格数据
data = dst_ds.GetRasterBand(1).ReadAsArray()
# 将栅格数据转换为二进制数组
binary_data = np.where(data == 255, 1, 0)
# 保存二进制数组为文本文件
np.savetxt('binary.txt', binary_data, fmt='%d')
```
假设我们要将一个名为“vector.shp”的矢量文件转换为栅格数据,代码将创建一个名为“raster.tif”的栅格数据集,并将其保存为二进制数组“binary.txt”。注意,这段代码仅将矢量文件中的一个图层转换为栅格数据,如果要转换多个图层,则需要对每个图层分别进行操作。