python使用post請求發送圖片並接受圖片


圖像讀取編碼與反編碼:

import requests
import json
import numpy as np
import cv2
import base64
 
# 首先將圖片讀入
# 由於要發送json,所以需要對byte進行str解碼
def getByte(path):
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read())
    img_str = img_byte.decode('ascii')
    return img_str
 
img_str = getByte('../face_/sample/heyang.jpg')
# 此時可以測試解碼得到圖像並顯示,服務器端也按照下面的方法還原圖像繼續進一步處理
img_decode_ = img_str.encode('ascii')  # ascii編碼
img_decode = base64.b64decode(img_decode_)  # base64解碼
img_np = np.frombuffer(img_decode, np.uint8)  # 從byte數據讀取為np.array形式
img = cv2.imdecode(img_np, cv2.COLOR_RGB2BGR)  # 轉為OpenCV形式
 
# 顯示圖像
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()

發送圖片到服務器:

import requests
import json
import base64
import socket
 
# 首先將圖片讀入
# 由於要發送json,所以需要對byte進行str解碼
def getByte(path):
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read())
    img_str = img_byte.decode('ascii')
    return img_str
 
img_str = getByte('../face_/sample/heyang.jpg')
# 此段為獲得ip,本人使用本機服務器測試
def getIp():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip
 
url = 'http://' + str(getIp()) + ':9888/'
data = {'recognize_img':img_str, 'type':'0', 'useAntiSpoofing':'0'}
json_mod = json.dumps(data)
res = requests.post(url=url, data=json_mod)
print(res.text)
# 如果服務器沒有報錯,傳回json格式數據
print(eval(res.text))

 

 

 

 

--


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM