【发布时间】:2018-07-12 17:48:55
【问题描述】:
我有一个接收图像、处理图像并返回响应的 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 发送图像的更好方法,请告诉我。
谢谢!
【问题讨论】:
-
这里
literal_eval的意思我没看懂。 -
@DanielRoseman
literal_eval将shape从字符串转换为元组。 -
绝不像你想要的那么紧凑,我有一个休息服务,我只是在发布之前对图像进行base64编码,然后在服务器上对其进行解码。我认为您的问题可能是将原始字节放入 JSON 请求中。我认为您不能将原始字节放入 JSON 中。例如,引号字符的字节将关闭值字符串。
-
谢谢@JohnMorris!
标签: python django numpy post encoding