将内存中的OpenCV映像写入BytesIO或Tempfile

Chr*_*lan 2 python opencv

我需要将位于内存中的OpenCV映像写入BytesIO或Tempfile对象,以在其他地方使用。

就我个人来说,这是一个死胡同的问题,因为cv2.imwrite()需要一个文件名作为参数,然后使用文件扩展名来推断图像类型来写(.jpg.png.tiff等)。cv2.imwrite()在C ++级别执行此操作,因此我担心无法成功将非文件名对象传递给它。

另一种可能的解决方案是转换为PILthrough numpy,它具有写入BytesIOTempfile对象的能力,但是我想避免不必要的复制。

Mad*_*Lee 6

cv2.imencode 可以帮助您:

import numpy as np
import cv2
import io

img = np.ones((100, 100), np.uint8)
# encode
is_success, buffer = cv2.imencode(".jpg", img)
io_buf = io.BytesIO(buffer)
# decode
decode_img = cv2.imdecode(np.frombuffer(io_buf.getbuffer(), np.uint8), -1)
print(np.allclose(img, decode_img))   # True
Run Code Online (Sandbox Code Playgroud)