使用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'>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)