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

47

我正在使用PyOpenCV。如何将cv2图像(numpy)转换为二进制字符串以写入MySQL数据库,而不需要临时文件和imwrite

我搜索了一下,但是没有找到...

我尝试使用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

帮助别人!

6个回答

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


5
在OpenCV3.0以上版本中,需要使用cv2.imdecode(nparr, cv2.IMREAD_COLOR)进行解码。 - ichbinblau
4
在NumPy中,推荐使用frombuffer()而不是fromstring(),那么使用tobytes()是否比tostring()更好呢? - feature_engineer
我的图片中有一种奇怪的脸红色,该如何修复?https://imgur.com/OxdO7HB - HB MAAM

10

使用numpy==1.19.4和opencv==4.4.0,可以在2020年成功运行:

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

7

这里有一个例子:

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

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

5

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

尝试将其拆分:

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

1
它返回的是(True, array([[137], [ 80], [ 78], ..., [ 66], [ 96], [130]], dtype=uint8)),而不是一个字节字符串。 - xercool
如何将其转换为字节字符串? - xercool
2
我的解决方案是 self.wfile.write(numpy.array(cv2.imencode('.png', img)[1]).tostring()) - xercool

3

这是我使用Python CGI与OpenCV的代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接