我通过reticulate
包使用某些python功能创建了一个函数,专门使用PIL
打开图像:
image <- "~/Desktop/image.jpg"
pil.image <- reticulate::import( "PIL.Image", convert = FALSE )
img <- pil.image$open( image )
然后我对图像做了一些事情(我提取了几种作物),这很好用。这是我正在做的事情的一个例子(outputs
是我需要的庄稼的数据框,因此crop.grid
只是4个数字的向量。
crop.grid <- c( outputs$x.start[x],
outputs$y.start[x],
outputs$x.stop[x],
outputs$y.stop[x] )
crop.grid <- as.integer( crop.grid )
crop.grid <- reticulate::r_to_py( crop.grid )
output.array <- img$crop( box = crop.grid )
output.array$save( output.filename )
在此之后,我想从内存中清除图像(我打开的图像非常大,因此占用大量内存)。我尝试在python中关闭图像:
img$close()
以及R:
rm( img )
gc()
用我知道的东西替换物体非常小。
img <- reticulate::r_to_py( 1L )
所有这些都运行良好,但我的RAM仍然记录为非常充分。我用我创建的每个python对象尝试它们,但唯一能有效清除RAM的是重启R会话。
我知道在python
内我最好使用with
打开图片,以便在流程结束时清除它,但我不确定如何使用reticulate
来实现它。
---使用类似的python
版本进行更新:
如果我直接在python中执行上述操作:
from PIL import Image
img = Image.open( "/home/user/Desktop/image.jpg" )
output = img.crop( [0,0,100,100] )
然后关闭事情:
output.close()
img.close()
记忆清除。同样的事情在R内部并没有起作用。即:
output.array$close()
img$close()
gc() # for good measure
不清除记忆。
答案 0 :(得分:4)
你需要做三件事:
在Python中显式创建对象:
py_env <- py_run_string(
paste(
"from PIL import Image",
"img = Image.open('~/Desktop/image.jpg')",
sep = "\n"
),
convert = FALSE
)
img <- py_env$img
完成图像后,首先删除Python对象。
py_run_string("del img")
然后运行Python垃圾收集器。
py_gc <- import("gc")
py_gc$collect()
步骤2和3是重要的。第1步就是让你有一个名字要删除。如果有办法删除“隐式”Python对象(想不出更好的术语),那将节省一些样板。