Python OpenCV是否将图像转换为字节字符串?

2024-05-05 14:10:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在和PyOpenCV一起工作。如何将cv2映像(numpy)转换为二进制字符串,以便在没有临时文件和imwrite的情况下写入MySQL db?

我搜索了一下,但什么也没找到。。。

我正在尝试imencode,但它不起作用。

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

救命啊!


Tags: 字符串selfnumpyurlreadpng二进制情况
3条回答
im = cv2.imread('/tmp/sourcepic.jpeg')
res, im_png = cv2.imencode('.png', im)
with open('/tmp/pic.png', 'wb') as f:
    f.write(im_png.tobytes())

如果您有一个图像img(这是一个numpy数组),可以使用以下命令将其转换为字符串:

>>> img_str = cv2.imencode('.jpg', img)[1].tostring()
>>> type(img_str)
 'str'

现在,您可以轻松地将图像存储在数据库中,然后使用以下方法进行恢复:

>>> nparr = np.fromstring(STRING_FROM_DATABASE, np.uint8)
>>> img = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)

需要用包含查询结果的变量替换STRING_FROM_DATABASE到包含图像的数据库。

read()返回一个元组(err,img)。

试着把它分开:

_,img = capture.read()
self.wfile.write(cv2.imencode('png', img))

相关问题 更多 >