python - 将图像发布到 Django REST API
问题描述
我有一个接收图像、处理图像并返回响应的 Django 项目。我正在编写一个脚本来测试我的 API,但是客户端发送的字节与服务器接收的字节不同。
客户端代码:
# client.py
from urllib.parse import urlencode
from urllib.request import Request, urlopen
import cv2
img = cv2.imread(image_file)
data = {'image': img.tobytes(), 'shape': img.shape}
data = urlencode(data).encode("utf-8")
req = Request(service_url, data)
response = urlopen(req)
print(response.read().decode('utf-8'))
查看代码:
# service/app/views.py
import ast
import numpy as np
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def process_image(request):
if request.method == 'POST':
# Converts string to tuple
shape = ast.literal_eval(request.POST.get('shape'))
img_bytes = request.POST.get('image')
# Reconstruct the image
img = np.fromstring(img_bytes, dtype=np.uint8).reshape(shape)
# Process image
return JsonResponse({'result': 'Hello'})
当我运行客户端代码时,我得到了ValueError: total size of new array must be unchanged
。我使用 8x8 RGB 图像进行了以下检查:
# client.py
>> print(img.shape)
(8, 8, 3)
>> print(img.dtype)
uint8
>> print(len(img.tobytes()))
192
# service/app/views.py
>> print(shape)
(8, 8, 3)
>> print(len(img_bytes))
187
该shape
字段还可以,但该字段的image
大小不同。由于图像很小,我从客户端和服务器打印了字节,但我没有得到相同的结果。我认为这是一个编码问题。
我想将图像作为字节发送,因为我认为这是发送此类数据的一种紧凑方式。如果有人知道通过 HTTP 发送图像的更好方法,请告诉我。
谢谢!
解决方案
受约翰莫里斯评论的启发,我在Numpy Array to base64 中找到了我的问题的答案,然后返回到 Numpy Array帖子。如果有人有同样的疑问,这里是解决方案:
客户端代码:
# client.py
import base64
from urllib.parse import urlencode
from urllib.request import Request, urlopen
import cv2
img = cv2.imread(image_file)
img_b64 = base64.b64encode(img)
data = {'image': img_b64, 'shape': img.shape}
data = urlencode(data).encode("utf-8")
req = Request(service_url, data)
response = urlopen(req)
print(response.read().decode('utf-8'))
查看代码:
# service/app/views.py
import ast
import base64
import numpy as np
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def process_image(request):
if request.method == 'POST':
shape = ast.literal_eval(request.POST.get('shape'))
buffer = base64.b64decode(request.POST.get('image'))
# Reconstruct the image
img = np.frombuffer(buffer, dtype=np.uint8).reshape(shape)
# Process image
return JsonResponse({'result': 'Hello'})
谢谢你们!
推荐阅读
- sql-server - 在 SQL 中查找没有特定值的记录
- python - 使用滑块重绘平面
- php - php preg_match 为相同的字符串返回不同的结果
- javascript - 只需要切换特定段落
- html - CSS Flex 项目垂直然后水平
- arrays - Excel - 获得#VALUE!只有一个例子。所有其他工作都很好
- google-bigquery - BigQuery 计划查询未附加
- xcode - 无法构建 cordova iOS 平台 -- 错误 65 allowProvisioningUpdates
- java - databaseSnapshot 空引用
- r - 在同一个图表中应用两种不同的填充(ggplot2)