Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Write OpenCV image in memory to BytesIO or Tempfile

I need to write an OpenCV image that sits in memory to a BytesIO or Tempfile object for use elsewhere.

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

cv2.imencode may help you:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...