python - 如何将 Django request.FILES (这是一个图像)作为二进制文件读取
问题描述
我想从请求中获取包含来自 ajax 的图像文件的二进制图像。
Senario - 当用户上传图像文件时,我想使用 google VISION API 对图像文件进行 OCR(光学字符识别)。为此,我需要将文件作为二进制文件读取。
背景 - 目前,在我的程序中,当用户上传图像时,文件通过 ajax 传递给 Django 视图。我试图在views.py 中获取一个二进制文件。当我使用request.FILES.get('file').read()
时,没有数据。但是print(request.FILES.get('file').name)
'bank.png'...我觉得很奇怪。
这是一些代码
视图.py
def receipt_ocr(request):
if request.method == 'POST':
print(type(request.FILES["file"])) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
print(type(request.FILES.get('file'))) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
print(request.FILES.get('file')) #bank.png
imageFile = request.FILES.get('file')
print(imageFile.size) #119227
print(request.FILES.get('file').name) #bank.png
print(request.FILES.get('file').content_type) #image/png
print(type(request.FILES.get('file').open())) #<class 'NoneType'>
print(request.FILES.get('file').open()) #None
print(type(request.FILES["file"].read())) #<class 'bytes'>
for chunk in imageFile.chunks():
print(chunk) #this generates lot of binary and some rdf:Description rdf:about= ... things
receipt_image = imageFile.read()
print(type(receipt_image))
print(receipt_image)
ajax部分
// receipt OCR process
$.ajax({
url: "{% url 'place:receipt_ocr' %}",
enctype: 'multipart/form-data',
type: 'POST',
processData: false,
contentType: false,
data: postData,
complete: function(req){
alert('good');
},
error: function(req, err){
alert('message:' + err);
}
});
我真正想做的是使用这种代码(google VISION API 示例代码,OCR)
def detect_text(path):
"""Detects text in the file."""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read() #read binary, save to content
image = vision.types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
print('Texts:')
print(type(texts))
for text in texts:
print('\n"{}"'.format(text.description))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in text.bounding_poly.vertices])
print('bounds: {}'.format(','.join(vertices)))
所以我想从请求中获取我的views.py中上述代码的“内容”。(我不需要使用这个函数本身。我将使用该函数的一部分)
如何在views.py 中获取二进制图像?我认为下面的代码会起作用,但它不起作用。我不知道为什么。
f = request.FILES.get('file')
receipt_image = f.read()
image = vision.types.Image(content=receipt_image)
感谢您的任何帮助和评论。
===添加===
“它不起作用”意味着我从日志中得到了这个 Traceback。
Internal Server Error: /mdd_event/receipt_ocr/ Traceback (most recent call last): File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\google\api_core\grpc_helpers.py", line 57, in error_remapped_callable return callable_(*args, **kwargs)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\grpc\_channel.py", line 565, in __call__ return _end_unary_response_blocking(state, call, False, None)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\grpc\_channel.py", line 467, in _end_unary_response_blocking raise _Rendezvous(state, None, None, deadline) grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with: status = StatusCode.INVALID_ARGUMENT details = "Request must specify image and features." debug_error_string = "{"created":"@1566165461.211000000","description":"Error received from peer ipv4:216.58.197.234:443","file":"src/core/lib/surface/call.cc","file_line":1052,"grpc_message":"Request must specify image and features.","grpc_status":3}" >
The above exception was the direct cause of the following exception: Traceback (most recent call last):
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs)
File "C:\Users\user\liam\dev\git\mdd_bean\mdd_event\views.py", line 530, in receipt_ocr response = client.text_detection(image=image)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\google\cloud\vision_helpers\decorators.py", line 101, in inner response = self.annotate_image(request, retry=retry, timeout=timeout)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\google\cloud\vision_helpers\__init__.py", line 72, in annotate_image r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\google\cloud\vision_v1\gapic\image_annotator_client.py", line 274, in batch_annotate_images request, retry=retry, timeout=timeout, metadata=metadata File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\google\api_core\gapic_v1\method.py", line 143, in __call__ return wrapped_func(*args, **kwargs)
File "C:\Users\user\liam\dev\git\mdd_bean_env\lib\site-packages\google\api_core\grpc_helpers.py", line 59, in error_remapped_callable six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from google.api_core.exceptions.InvalidArgument: 400 Request must specify image and features.
解决方案
推荐阅读
- android - 将地图划分到不同的区域Android Studio?
- c# - 如何在月历 C# 中手动设置特定的开始日期
- c# - 我想使用正则表达式从这个字符串 GRN/GSI/2017/7 中提取 7
- django - 使用 travis 编码环境变量的 Django 和 travis CI 密钥错误
- php - 在php中将1.5的值四舍五入到1?
- asp.net-mvc - 从表单 MVC 中获取价值
- python - 更有效地执行嵌套 python 循环
- postgresql - 如何接受 postgresql 中的任何日期?
- css - 如何使用 Angular 4 及以上版本的 webpack.config 将 sass 与编译集成到 css 中?
- amazon-web-services - 如何排除某些 AWS S3 存储桶文件