簡體   English   中英

使用 rpy2 將圖像數據從 R 返回到 Python

[英]Using rpy2 to return image data from R to Python

我正在 R 中創建一個繪圖,但隨后嘗試將生成的圖像數據返回給 Python,以便 Python 可以顯示圖像。

在 R 中,我使用magick將圖像保存在內存中(而不是繪制到屏幕上)。

“我們使用image_write將任何格式的圖像導出到磁盤上的文件中,如果path = NULL則在內存中”

我不確定如何處理要么SexpExtPtrByteVector由返回類型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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM