python - 使用 rpy2 将图像数据从 R 返回到 Python
问题描述
我正在 R 中创建一个绘图,但随后尝试将生成的图像数据返回给 Python,以便 Python 可以显示图像。
在 R 中,我使用magick
库将图像保存在内存中(而不是绘制到屏幕上)。
“我们用于
image_write
将任何格式的图像导出到磁盘上的文件中,或者在内存中path = NULL
”
我不确定如何处理Python返回的SexpExtPtr
或ByteVector
类型。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 中:
figure
有类型<class 'rpy2.rinterface.SexpExtPtr'>
image
有类型<class 'rpy2.robjects.vectors.ByteVector'>
解决方案
所以......事实证明这<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()
推荐阅读
- php - 对于图像的每个像素,它将具有什么像素值?
- sql - Access 2013 - 使用每列的不同标准更新数据表
- mongodb - 如何使用 Mongodb 在 golang 中通过批量更新获取更新的文档 ID
- javascript - 将数组的值填充到复选框的布尔值
- graphics - VB6 支持哪些图像类型?
- typescript - typescript type definiton - 接口引用一个类型,但用作值
- spring - 如何使用一个数据源以编程方式更改 Spring 3.x 中的数据库?
- kubernetes - 如何在 GCP 中的 kubernetes 负载均衡器上通过客户端 IP 启用会话亲和性
- ruby-on-rails - ActiveAdmin - 操作“显示”不适用于复合主键
- c# - 如何在 EF Core 2 中使用外键作为复合键?