![](/img/trans.png)
[英]Run R script in python using data from python in the R script (rpy2)
[英]Using rpy2 to return image data from R to Python
我正在 R 中創建一個繪圖,但隨后嘗試將生成的圖像數據返回給 Python,以便 Python 可以顯示圖像。
在 R 中,我使用magick
庫將圖像保存在內存中(而不是繪制到屏幕上)。
“我們使用
image_write
將任何格式的圖像導出到磁盤上的文件中,如果path = NULL
則在內存中”
我不確定如何處理要么SexpExtPtr
或ByteVector
由返回類型rpy2
到Python。
import rpy2.robjects as ro
r = ro.r
r('''
library("magick")
figure <- image_graph(width = 400, height = 400, res = 96)
plot(c(1,2,3))
image <- image_write(figure, path = NULL, format = "png")
# image_write(figure, path = 'example.png', format = 'png')
''')
figure = ro.globalenv['figure']
image = ro.globalenv['image']
im = Image.open(BytesIO(image))
上面的代碼給了我錯誤:
Traceback (most recent call last):
File "stackoverflow.py", line 23, in <module>
im = Image.open(BytesIO(image))
TypeError: a bytes-like object is required, not 'ByteVector'
在 Python 中:
figure
類型為<class 'rpy2.rinterface.SexpExtPtr'>
image
類型為<class 'rpy2.robjects.vectors.ByteVector'>
所以......事實證明<class 'rpy2.robjects.vectors.ByteVector'>
是一個可迭代的,我可以使用bytes()
來構造一個字節數組。
此外,通過將代碼放在使用return
返回 PIL 圖像的函數中,我可以讓圖像顯示在 Jupyter notebook 中(或者我們可以只執行image.show()
)
from io import BytesIO
import PIL.Image as Image
import rpy2.robjects as ro
def main():
r = ro.r
r('''
library("magick")
figure <- image_graph(width = 400, height = 400, res = 96)
plot(c(1,2,3))
image <- image_write(figure, path = NULL, format = "png")
image_write(figure, path = 'example.png', format = 'png')
''')
image_data = ro.globalenv['image']
image = Image.open(BytesIO(bytes(image_data)))
return image
if __name__ == '__main__':
image = main()
image.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.