首页 > 解决方案 > 将图像发布到 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 发送图像的更好方法,请告诉我。

谢谢!

标签: pythondjangonumpypostencoding

解决方案


受约翰莫里斯评论的启发,我在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'})

谢谢你们!


推荐阅读