gpt4 book ai didi

R 网状,如何从内存中清除 python 对象?

转载 作者:行者123 更新时间:2023-12-04 04:24:18 25 4
gpt4 key购买 nike

我已经通过 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 session 。

我知道在 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 中不起作用。 IE:
output.array$close()
img$close()
gc() # for good measure

不清除内存。

最佳答案

你需要做3件事:

  • 在 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 对象(想不出更好的术语),那将节省一些样板。

    关于R 网状,如何从内存中清除 python 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44379525/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com