Python OpenCV convert image to byte string?(Python OpenCV将图像转换为字节字符串?)
问题描述
我正在使用 PyOpenCV.如何在没有临时文件和 imwrite 的情况下将 cv2 图像(numpy)转换为二进制字符串以写入 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 数组),你可以使用以下方法将其转换为字符串:
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'
现在您可以轻松地将图像存储在数据库中,然后使用以下方法恢复它:
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 替换为包含对包含图像的数据库的查询结果的变量.
where you need to replace STRING_FROM_DATABASE with the variable that contains the result of your query to the database containing the image.
这篇关于Python OpenCV将图像转换为字节字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python OpenCV将图像转换为字节字符串?
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
