【问题标题】:Python OpenCV convert image to byte string?Python OpenCV将图像转换为字节字符串?
【发布时间】:2013-07-31 19:09:00
【问题描述】:

我正在使用 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

帮助别人!

【问题讨论】:

    标签: python image opencv binary


    【解决方案1】:

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

    【讨论】:

    • opencv3.0+必须使用cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    • tobytes() 并不比 tostring() 好,就像 numpy 建议使用 frombuffer() 而不是 fromstring() 一样?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      尝试拆分:

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

      【讨论】:

      • 它返回 (True, array([[137], [80], [78], ..., [66], [96], [130]], dtype=uint8)) ,但不是字节串
      • 如何将其转换为字节串?
      • 我的解决方案是self.wfile.write(numpy.array(cv2.imencode('.png', img)[1]).tostring())
      【解决方案4】:
      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】:

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

        【讨论】:

          【解决方案6】:

          这是一个例子:

          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
          

          【讨论】:

            猜你喜欢
            • 2017-08-16
            • 2019-02-12
            • 2013-04-18
            • 2015-03-29
            • 1970-01-01
            • 1970-01-01
            • 2019-12-05
            • 2017-01-19
            • 2018-11-30
            相关资源
            最近更新 更多