我有个朋友。我想用csv表中相应的值替换光栅中的值。你知道吗
光栅的类值为0到n,csv为光栅的每个类n都有一个计算值(例如点密度)。 我想从csv中的相应值创建一个新光栅
我正在使用GDAL和numpy。我试过使用pandas,但遇到了从csv提取值到光栅pandas数据帧的问题。我将在对应csv表的光栅列表上执行此操作。你知道吗
下面是我的数据示例(一个光栅)
#Example raster array
[5 2 2 3
0 3 1 4
2 0 1 3]
#Corresponding csv table
Class Count Density
0 2 6
1 2 9
2 2 4
3 3 9
4 1 7
5 1 2
#Output Raster (to take the corresponding density values,
#i.e. if class = 0, then output raster = 6, the corresponding density value)
[2 4 4 9
6 9 9 7
4 6 9 9]
我有从光栅创建数组和从数组写回光栅的代码。我从不同的stackexchange网站上发现的。 我不知道如何框循环,以获得新光栅中的csv值。 我下面的for循环代码不完整。 有人能帮忙吗
import numpy, sys
from osgeo import gdal
from osgeo.gdalconst import *
inRst = gdal.Open(r"c:/Raster1.tif")
band = inRst.GetRasterBand(1)
rows = inRst.RasterYSize
cols = inRst.RasterXSize
rstr_arry = band.ReadAsArray(0,0,cols,rows)
# create the output image
driver = inRst.GetDriver()
#print driver
outRst = driver.Create(r"c:/NewRstr.tif", cols, rows, 1, GDT_Int32)
outBand = outRst.GetRasterBand(1)
outData = numpy.zeros((rows,cols), numpy.int32)
for i in range(0, rows):
for j in range(0, cols):
if rstr_arry[i,j] = :
outData[i,j] =
elif rstr_arry[i,j] = :
outData[i,j] =
else:
outData[i,j] =
# write the data
outRst= outBand.WriteArray(outData, 0, 0)
# flush data to disk, set the NoData value and calculate stats
outBand.FlushCache()
outBand.SetNoDataValue(-99)
# georeference the image and set the projection
outDs.SetGeoTransform(inDs.GetGeoTransform())
outDs.SetProjection(inDs.GetProjection())
如果我没有误解您想要实现的目标,那么您首先必须读取csv文件并创建
Class
值到Density
值的映射。可以这样做:您将获得如下
dict
:然后可以使用^{} 创建需要替换的元素的掩码矩阵,并使用^{} 替换元素。在执行此操作之前,需要展平光栅阵列,并在写回结果之前恢复其形状。
(替换numpy数组中元素的替代方法可以在以下问题的答案中找到:Fast replacement of values in a numpy array)
然后,您可以按照计划编写数据几乎:
在示例数据上进行测试:
相关问题 更多 >
编程相关推荐