将内存中的OpenCV映像写入BytesIO或Tempfile [英] Write OpenCV image in memory to BytesIO or Tempfile
问题描述
我需要将内存中的OpenCV映像写入BytesIO或Tempfile对象,以供其他地方使用.
I need to write an OpenCV image that sits in memory to a BytesIO or Tempfile object for use elsewhere.
我担心这是一个死胡同的问题,因为cv2.imwrite()
将文件名作为参数,然后使用文件扩展名来推断要写入的图像类型(.jpg
,.png
,.tiff
,等等.). cv2.imwrite()
在C ++级别执行此操作,因此我担心无法成功将非文件名对象传递给它.
I am concerned this is a dead end question, because cv2.imwrite()
takes a filename as an argument, and then uses the file extension to infer the image type to write (.jpg
, .png
, .tiff
, etc.). cv2.imwrite()
does this at the C++ level, so I am concerned that there is no way to successfully pass a non-filename object to it.
另一种可能的解决方案是通过numpy
转换为PIL
,该功能可以写入BytesIO
和Tempfile
对象,但我想避免不必要的复制.
The other possible solution is converting to PIL
through numpy
, which has the capacity to write to BytesIO
and Tempfile
objects, but I want to avoid needless copies.
推荐答案
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
这篇关于将内存中的OpenCV映像写入BytesIO或Tempfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!