Python OpenCV Image to byte string for json transfer

后端 未结 2 1190
时光取名叫无心
时光取名叫无心 2020-12-23 10:10

I use python3 with numpy, scipy and opencv.

I\'m trying to convert a image read through OpenCV and connected camera interface into

相关标签:
2条回答
  • 2020-12-23 10:33

    You do not need to save the buffer to a file. The following script captures an image from a webcam, encodes it as a JPG image, and then converts that data into a printable base64 encoding which can be used with your JSON:

    import cv2
    import base64
    
    cap = cv2.VideoCapture(0)
    retval, image = cap.read()
    retval, buffer = cv2.imencode('.jpg', image)
    jpg_as_text = base64.b64encode(buffer)
    print(jpg_as_text)
    cap.release()
    

    Giving you something starting like:

    /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCg
    

    This could be extended to show how to convert it back to binary and then write the data to a test file to show that the conversion was successful:

    import cv2
    import base64
    
    cap = cv2.VideoCapture(0)
    retval, image = cap.read()
    cap.release()
    
    # Convert captured image to JPG
    retval, buffer = cv2.imencode('.jpg', image)
    
    # Convert to base64 encoding and show start of data
    jpg_as_text = base64.b64encode(buffer)
    print(jpg_as_text[:80])
    
    # Convert back to binary
    jpg_original = base64.b64decode(jpg_as_text)
    
    # Write to a file to show conversion worked
    with open('test.jpg', 'wb') as f_output:
        f_output.write(jpg_original)
    

    To get the image back as an image buffer (rather than JPG format) try:

    jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
    image_buffer = cv2.imdecode(jpg_as_np, flags=1)
    
    0 讨论(0)
  • 2020-12-23 10:50

    Some how the above answer doesn't work for me, it needs some update. Here is the new answer to this:

    To encode for JSON:

    import base64
    import json
    import cv2
    
    img = cv2.imread('./0.jpg')
    string = base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()
    dict = {
        'img': string
    }
    with open('./0.json', 'w') as outfile:
        json.dump(dict, outfile, ensure_ascii=False, indent=4)
    

    To decode back to np.array:

    import base64
    import json
    import cv2
    import numpy as np
    
    response = json.loads(open('./0.json', 'r').read())
    string = response['img']
    jpg_original = base64.b64decode(string)
    jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
    img = cv2.imdecode(jpg_as_np, flags=1)
    cv2.imwrite('./0.jpg', img)
    

    Hope this could help someone :P

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