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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17967320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:37:20  来源:igfitidea点击:

Python OpenCV convert image to byte string?

pythonimageopencvbinary

提问by xercool

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?

我正在使用 PyOpenCV。如何将 cv2 图像(numpy)转换为二进制字符串,以便在没有临时文件的情况下写入 MySQL 数据库和imwrite

I googled it but found nothing...

我用谷歌搜索,但什么也没找到……

I'm trying imencode, but it doesn't work.

我正在尝试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()))

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!

帮助某人!

回答by berak

capture.read() returns a tuple, (err,img).

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

try splitting it up:

尝试拆分它:

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

回答by themadmax

My code to use opencv with python cgi :

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

回答by jabaldonedo

If you have an image img(which is a numpy array) you can convert it into string using:

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

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

where you need to replace STRING_FROM_DATABASEwith the variable that contains the result of your query to the database containing the image.

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

回答by remort

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

回答by CKboss

Here is an example:

下面是一个例子:

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