43

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...

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()))

Error:

  File "server.py", line 16, in do_GET
  self.wfile.write(cv2.imencode('png', capture.read()))
  TypeError: img is not a numerical tuple

Help somebody!

4

6 回答 6

78

如果您有图像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用包含查询结果的变量替换包含图像的数据库。

于 2014-08-31T14:31:48.587 回答
9

它在 2020 年适用于 numpy==1.19.4 和 opencv==4.4.0:

import cv2

cam = cv2.VideoCapture(0)

# get image from web camera
ret, frame = cam.read()

# convert to jpeg and save in variable
image_bytes = cv2.imencode('.jpg', frame)[1].tobytes()
于 2020-11-15T20:52:44.007 回答
5

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

尝试拆分它:

_,img = capture.read()
self.wfile.write(cv2.imencode('png', img))
于 2013-07-31T12:46:14.520 回答
5
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())
于 2019-06-26T13:20:05.573 回答
5

这是一个例子:

def image_to_bts(frame):
    '''
    :param frame: WxHx3 ndarray
    '''
    _, bts = cv2.imencode('.webp', frame)
    bts = bts.tostring()
    return bts

def bts_to_img(bts):
    '''
    :param bts: results from image_to_bts
    '''
    buff = np.fromstring(bts, np.uint8)
    buff = buff.reshape(1, -1)
    img = cv2.imdecode(buff, cv2.IMREAD_COLOR)
    return img
于 2019-09-15T11:47:57.610 回答
3

我将 opencv 与 python cgi 一起使用的代码:

    im_data = form['image'].file.read()
    im = cv2.imdecode( np.asarray(bytearray(im_data), dtype=np.uint8), 1 )
    ret, im_thresh = cv2.threshold( im, 128, 255, cv2.THRESH_BINARY )
    self.send_response(200)
    self.send_header("Content-type", "image/jpg")
    self.end_headers()      
    ret, buf = cv2.imencode( '.jpg', im_thresh )
    self.wfile.write( np.array(buf).tostring() )
于 2014-05-13T15:09:01.477 回答