使用 rpy2 从 Python 调用 R writeRaster

发布于 2025-01-12 04:11:47 字数 619 浏览 0 评论 0原文

我在 Python 代码中使用 R 包来导入、处理和保存 GeoTIFF 栅格。导入和处理工作正常,但我很难再次保存光栅文件。这是我正在运行的代码的简化版本:

import rpy2.rinterface as ri
import rpy2.robjects as rob
import rpy2.robjects.packages as rpackages

raster  = rpackages.importr('raster')

r_raster = raster.raster(geotiff_input_path)

# r_raster = process_raster(r_raster)

raster.writeRaster(r_raster, geotiff_output_path, overwrite=True)

但是,代码失败并显示 AttributeError: module 'raster' has no attribute 'writeRaster'

我似乎误解了如何正确调用 writeRaster

I am using an R package within my Python code to import, process and save a GeoTIFF raster. The importing and processing works just fine, but I struggle to save the raster file again. This is a simplified version of the code I'm running:

import rpy2.rinterface as ri
import rpy2.robjects as rob
import rpy2.robjects.packages as rpackages

raster  = rpackages.importr('raster')

r_raster = raster.raster(geotiff_input_path)

# r_raster = process_raster(r_raster)

raster.writeRaster(r_raster, geotiff_output_path, overwrite=True)

However, the code fails with AttributeError: module 'raster' has no attribute 'writeRaster'.

I seem to misunderstand how to call writeRaster properly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤云独去闲 2025-01-19 04:11:47

我通过从 R 对象中调用 writeRaster 函数来修复此问题:

import os
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects

os.environ['R_HOME'] = r'C:\Program Files\R\R-4.2.3'

raster = importr('raster')
    
robjects.globalenv["rasterpath"] = rasterpath
robjects.globalenv["raster"] = raster
robjects.r('writeRaster(raster, rasterpath, format="GTiff", overwrite=TRUE)')
    

使用 robjects.globalenv[''] 函数声明 robjects 后,您可以将它们用作实际局部变量的对象。因此,您可以在字符串中使用 R 表示法书写。

I fixed it by calling the writeRaster function from within a R object:

import os
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects

os.environ['R_HOME'] = r'C:\Program Files\R\R-4.2.3'

raster = importr('raster')
    
robjects.globalenv["rasterpath"] = rasterpath
robjects.globalenv["raster"] = raster
robjects.r('writeRaster(raster, rasterpath, format="GTiff", overwrite=TRUE)')
    

Once you declare the robjects with the robjects.globalenv[''] function, you can use them as objects of your actual local variables. Therefore, you can write within the string with R notation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文