第一种:文件路径,需要先存储为本地图片然后再读
def head_detect(request):
if request.method == “POST”:
img_d = request.FILES.get(‘img_path’)
if img_d == None:
err_info = {‘code’:1,‘msg’:‘img is null’}
return JsonResponse(err_info)
elif img_d > 2097152:
size_info = {‘code’: 2, ‘msg’: ‘img size is too large’}
return JsonResponse(size_info)
else:
file_img = open(os.path.join(‘result_img’, img_d.name), “wb”)
for filex in img_d.chunks():
file_img.write(filex)
img_path_name = os.path.join(‘result_img’,img_d.name)
img = cv2.imread(img_path_name)
os.remove(img_path_name)
call_json = detect(img)
return JsonResponse(call_json)
第二种:base64(相对占用存储空间)
def argparse_base64_opencv(img_base64):
‘’’
解析base64格式的img为python’s numpy格式的img
:param img_base64: base64格式的img
:return: python numpy格式的img
‘’’
img_b64decode = base64.b64decode(img_base64) # base64解码
img_array = np.fromstring(img_b64decode,np.uint8) # 转换np序列
img_numpy=cv2.imdecode(img_array,cv2.COLOR_BGR2RGB) # 转换Opencv格式
return img_numpy
def head_detect(request):
if request.method == “POST”:
try:
request_dict = json.loads(request.body.decode())
except:
request_dict = request.POST
img_base64 = request_dict.get(‘img_base64’)
img = argparse_base64_opencv(img_base64)
call_json = detect(img)
return JsonResponse(call_json)
第三种 文件流
def head_detect(request):
if request.method == “POST”:
try:
pic = request.FILES.get(‘img_path’)
if pic == None:
err_info = {‘code’:1,‘msg’:‘img is null’}
return JsonResponse(err_info)
elif len(pic) > 2097152: # 2M
size_info = {‘code’: 2, ‘msg’: ‘img size is too large’}
return JsonResponse(size_info)
else:
img_pil = Image.open(pic)
if len(img_pil.split()) == 4:
r,g,b,a = img_pil.split()
img3 = Image.merge(“RGB”,(r,g,b))
img = np.asarray(img3)
call_json = detect(img)
return JsonResponse(call_json)
else :
img = np.asarray(img_pil)
img == img[:,:,::-1]
call_json = detect(img)
return JsonResponse(call_json)