問題描述
我正在使用 PyOpenCV.如何在沒有臨時文件和 imwrite
的情況下將 cv2 圖像(numpy)轉(zhuǎn)換為二進(jìn)制字符串以寫入 MySQL db?
I'm working with PyOpenCV. How to convert cv2 image (numpy) to binary string for writing to MySQL db without a temporary file and imwrite
?
我用谷歌搜索了它,但什么也沒找到......
I googled it but found nothing...
我正在嘗試 imencode
,但它不起作用.
I'm trying imencode
, but it doesn't work.
capture = cv2.VideoCapture(url.path)
capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, float(url.query))
self.wfile.write(cv2.imencode('png', capture.read()))
錯誤:
File "server.py", line 16, in do_GET
self.wfile.write(cv2.imencode('png', capture.read()))
TypeError: img is not a numerical tuple
幫助別人!
推薦答案
如果你有一個圖像 img
(這是一個 numpy 數(shù)組),你可以使用以下方法將其轉(zhuǎn)換為字符串:
If you have an image img
(which is a numpy array) you can convert it into string using:
>>> img_str = cv2.imencode('.jpg', img)[1].tostring()
>>> type(img_str)
'str'
現(xiàn)在您可以輕松地將圖像存儲在數(shù)據(jù)庫中,然后使用以下方法恢復(fù)它:
Now you can easily store the image inside your database, and then recover it by using:
>>> nparr = np.fromstring(STRING_FROM_DATABASE, np.uint8)
>>> img = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)
您需要將 STRING_FROM_DATABASE
替換為包含對包含圖像的數(shù)據(jù)庫的查詢結(jié)果的變量.
where you need to replace STRING_FROM_DATABASE
with the variable that contains the result of your query to the database containing the image.
這篇關(guān)于Python OpenCV將圖像轉(zhuǎn)換為字節(jié)字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!