有没有一种方法可以在不先保存到文件的情况下操作图像?

is there a way to manipulate image without saving to a file first?

我正在尝试为我的 ML/DL 项目收集 img 数据。

我需要面部数据,所以我必须检测面部并在其周围裁剪。

我有一堆我在网上搜索的 img 网址。

通常我会使用请求库将它们保存在文件中,但是否可以在内存中进行?

response = requests.get(IMG_URL)
img_byte = response.content
# Do image processing without saving to a file

我查看了python中的一些图像库,例如 PIL 或 OpenCV,

但他们似乎都首先从文件中加载图像。

我想如果不保存临时文件我可以加快这个过程。 (I/O是个大瓶颈)

我尝试使用 BytesIO 函数,但我无法弄明白。

BytesIO 是要走的路!。您可以将请求返回的二进制数据存储到 In-memory byte buffer(BytesIO) and pass it to Image.open

>>> from PIL import Image
>>> from io import BytesIO
>>> img_obj = Image.open(BytesIO(r.content))

Image.open API 的唯一要求是 fp 参数必须是 文件名(字符串)、pathlib.Path 对象或 a文件对象。文件对象必须实现 file.readfile.seekfile.tell 方法,并以二进制模式打开.

BytesIO 实现了所有这些方法。

>>> from io import BytesIO
>>>
>>> buffer = BytesIO()
>>> hasattr(buffer, 'read') and hasattr(buffer, 'tell') and hasattr(buffer, 'seek')
True