使用rpy2将图像数据从R返回到Python

问题描述

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

在R中,我已将magick库用于hold the image in memory(而不是绘制到屏幕上)。

“我们使用image_write将任何格式的图像导出到磁盘上的文件中,或者如果有path = NULL则导出到内存中的文件中”

我不确定如何处理SexpExtPtr返回给Python的ByteVectorrpy2类型。

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笔记本中(或者我们可以只做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()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...