Read a base64 encoded image from memory using OpenCv python library

前端 未结 3 1329
梦谈多话
梦谈多话 2020-12-05 07:38

I\'m working on an app that to do some facial recognition from a webcam stream. I get base64 encoded data uri\'s of the canvas and want to use it to do something like this:<

相关标签:
3条回答
  • 2020-12-05 08:11

    You can just use both cv2 and pillow like this:

    import base64
    from PIL import Image
    import cv2
    from StringIO import StringIO
    import numpy as np
    
    def readb64(base64_string):
        sbuf = StringIO()
        sbuf.write(base64.b64decode(base64_string))
        pimg = Image.open(sbuf)
        return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR)
    
    cvimg = readb64('R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7')
    cv2.imshow(cvimg)
    
    0 讨论(0)
  • 2020-12-05 08:31

    This worked for me, and doesn't require PIL/pillow or any other dependencies (except cv2):

    import cv2
    import numpy as np
    
    def data_uri_to_cv2_img(uri):
        encoded_data = uri.split(',')[1]
        nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        return img
    
    data_uri = "data:image/jpeg;base64,/9j/4AAQ..."
    img = data_uri_to_cv2_img(data_uri)
    cv2.imshow(img)
    
    0 讨论(0)
  • 2020-12-05 08:36

    This is my solution for python 3.7 and without using PIL

    import base64
    
    def readb64(uri):
       encoded_data = uri.split(',')[1]
       nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
       img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
       return img
    

    i hope that this solutions works for all

    0 讨论(0)
提交回复
热议问题