首页 > 解决方案 > 使用 rpy2 将图像数据从 R 返回到 Python

问题描述

我正在 R 中创建一个绘图,但随后尝试将生成的图像数据返回给 Python,以便 Python 可以显示图像。

在 R 中,我使用magick将图像保存在内存中(而不是绘制到屏幕上)。

“我们用于image_write将任何格式的图像导出到磁盘上的文件中,或者在内存中path = NULL

我不确定如何处理Python返回的SexpExtPtrByteVector类型。rpy2

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 中:

标签: pythonrimagemagickrpy2

解决方案


所以......事实证明这<class 'rpy2.robjects.vectors.ByteVector'>是一个可迭代的,我可以bytes()用来构造一个字节数组。

Also, by putting the code inside a function that uses return to return the PIL image I can get the image to display within a Jupyter notebook (alternatively we could just do 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()

推荐阅读