问题描述
def post(self):
data = parser.parse_args()
if not data['file']:
abort(404,message="No images found")
imagestr = data['file'].read()
if imagestr:
#convert string data to numpy array
npimg = np.frombuffer(imagestr,np.uint8)
# convert numpy array to image
img = cv2.imdecode(npimg,cv2.IMREAD_UNCHANGED)
客户端代码:
def detect(image):
endpoint = "http://127.0.0.1/getimage"
# imstring = base64.b64encode(cv2.imencode('.jpg',image)[1]).decode()
# img_str = cv2.imencode('.jpg',image)
# im = img_str.tostring()
# jpg_as_text = base64.b64encode(buffer)
# print(jpg_as_text)
data = cv2.imencode('.jpg',image)[1].tobytes()
files = {'file':data}
headers={"content-type":"image/jpg"}
response = requests.post(endpoint,files=files,headers=headers)
return response
对于API,我能够通过CURL成功发送图像并获得响应。
curl -X POST -F file=@input.jpg http://127.0.0.1/getimage
但是,当我尝试使用客户端代码时,无法发送图像。我看到服务器端没有收到文件:
{'file': None}
192.168.101.57 - - [17/Aug/2020 14:56:39] "POST /getimage HTTP/1.1" 404 -
我不确定我缺少什么。有人可以帮忙吗?
解决方法
根据request docs,您应该使用以下方法发布文件:
files = {'file': ('image.jpg',open('image.jpg','rb'),'image/jpg',{'Expires': '0'})}
response = requests.post(endpoint,files=files)
,
我个人使用这种方法,因为它不仅可以发送图像,而且还可以发送任何 numpy数组,并进行一些压缩以减小大小。 (在您要发送图像数组(4d numpy数组)时很有用)
客户端代码:
import io,zlib
def encode_ndarray(np_array): #utility function
bytestream = io.BytesIO()
np.save(bytestream,np_array)
uncompressed = bytestream.getvalue()
compressed = zlib.compress(uncompressed,level=1) #level can be 0-9,0 means no compression
return compressed
any_numpy_array = np.zeros((4,150,3))
encoded_array = encode_ndarray(any_numpy_array)
headers = {'Content-Type': 'application/octet-stream'}
resp = requests.post(endpoint,data=encoded_array,headers=headers)
服务器端代码:
def decode_ndarray(bytestream): #utility function
return np.load(io.BytesIO(zlib.decompress(bytestream)))
@app.route("/getimage",methods=['POST'])
def function():
r = request
any_numpy_array = decode_ndarray(r.data)