圖像base64與numpy array之間的轉換

環境python3.6

import base64
import cv2
import numpy as np

1.base64 string to numpy array

image_string = request_data['image']
img_data = base64.b64decode(image_string)
nparr = np.fromstring(img_data, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

2. numpy array to base64 string

retval, buffer = cv2.imencode('.jpg', pic_img)
pic_str = base64.b64encode(buffer)
pic_str = pic_str.decode()

3. image file to base64 directly

with open(img_path, "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read())
    req_file = encoded_image.decode('utf-8')

4. post request using the base64 string as part of json parameters

import requests
import json
with open(img_path, "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read())
    req_file = encoded_image.decode('utf-8')
#json format parameters
post_dict = {"image": req_file, "type": 0}
headers = {
    'Content-Type': 'application/json',  # This is important
}
response = requests.post(url, data=json.dumps(post_dict), headers=headers)

#the host using jsonify(from flask) to return the result
result = json.loads(response.content.decode('utf8'))
pic_str = result['data']['pic_str']
pic_str = pic_str.encode('utf-8')
jpg_original = base64.b64decode(pic_str)
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
image_buffer = cv2.imdecode(jpg_as_np, flags=1)
cv2.imshow("asd", image_buffer)
cv2.waitKey(0)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章