【发布时间】:2022-01-05 21:15:45
【问题描述】:
我正在尝试使用 python 中的 rasterio 包将光栅图像划分为 for 循环的一部分(光栅图像就像地理空间分析世界中的矩阵/像素数组),但是我无法弄清楚目录问题.我实际上是在尝试遍历文件夹中的文件,然后将每个文件除以目标文件,然后生成唯一的输出产品文件。
我有以下代码:
#I am just interested in files containing these strings
d = ['Blue', 'Red', 'Green']
test = 'Colors/test_value.tif'
folder = Path('Colors')
src = rasterio.open(test)
#Loop through all the '.tif' files in the folder, but only those that contain 'Blue, Red, or Green in the file name
for f in folder.glob("*.tif"):
if any(color in f.name for color in d):
med = rasterio.open(f)
new_raster = med.read(1)/src.read(1)
# write raster
profile = src.profile
profile.update(
dtype=new_raster.dtype,
count=1,
compress='lzw')
#Create the output files with each unique file name
with rasterio.open(f"Colors/Output_Raster_{f}.tif", 'w', **profile) as dst:
dst.write(new_raster, 1)
所以我在引用的“文件夹”中有 4 个感兴趣的文件。它们是:Raster_Blue.tif、Raster_Red.tif、Raster_Green.tif 和 Raster_test.tif。我想遍历文件夹并将每个文件除以“Raster_test.tif”。但是,我只想将蓝色、红色和绿色文件用于我的操作,因此我不想运行“Raster_test.tif”除以“Raster_test.tif”。
因此,这段代码试图遍历文件夹中文件名字符串中包含“蓝色”、“红色”和“绿色”的文件,并且对于每次迭代,将特定颜色文件除以 @987654326 @。然后我想写那些输出文件。挑战在于,对于这些输出文件中的每一个,总共三个,对于循环将经历的三个迭代,我想给它们每个一个唯一的文件名,所以文件不只是每次都被覆盖。所以我想产生Output_Raster_Blue.tif、Output_Raster_Red.tif和Output_Raster_Green.tif。但是,当我尝试此代码时,我收到此错误消息:RasterioIOError: Attempt to create new tiff file 'Colors/Output_Raster_Colors\Output_Raster_Red.tif.tif' failed: No such file or directory
我的目标目录和文件名字符串似乎有点混乱,我无法弄清楚如何解决这个问题,或者为什么会发生这种情况。如何修复循环以便引用正确的目录?
【问题讨论】:
标签: python directory raster write rasterio