Postman发出的数据django接收转化成python的numpy的三种方式

第一种:文件路径,需要先存储为本地图片然后再读
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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值