【发布时间】:2021-10-19 09:44:38
【问题描述】:
所以,我想做的是用户输入一个 base64 编码的图像,然后通过 pytesseract OCR 将其转换为文本。问题是每次我尝试输入它时只会重新加载页面而没有任何反应。
这是我的 html sn-p :
<form method="POST" action="{% url 'ocr-view'%}"> {% csrf_token %}
<label for="base64"> Input Base64 :</label>
<input type="text" class="form-control" id="text" name="base64" />
<button type="submit" class="btn btn-primary mt-3" name="submit">
<i class="fas fa-search"></i>
Submit
</button>
</form>
<div class="card-body">
<label> Result : </label> <br>
<span class="h3">{{text}}</span>
</div>
这是我的意见.py:
class IndexView(LoginRequiredMixin, CreateView):
model = Ocr
template_name = "ocr/ocr.html"
fields = ['input']
def get_context_data (self):
text = ""
if self.request.method == 'POST':
imgstring = self.request.POST.get('base64')
imgstring = imgstring.split('base64,')[-1].strip()
image_string = BytesIO(base64.b64decode(imgstring))
image = Image.open(image_string)
text = pytesseract.image_to_string(image)
text = text.encode("ascii", "ignore")
text = text.decode()
context = {
'text': text,
}
return context
网址.py:
from django.urls import path
from .views import IndexView
urlpatterns = [
path("", IndexView.as_view(), name="ocr-view"),
path('<int:pk>/', IndexView.as_view(), name='ocr-input'),
]
但是如果我将 base64 代码直接放到views.py 中,OCR 功能就可以完美运行。
imgstring = 'data:image/jpeg;base64,/9j/somerandomcode'
imgstring = imgstring.split('base64,')[-1].strip()
image_string = BytesIO(base64.b64decode(imgstring))
image = Image.open(image_string)
text = pytesseract.image_to_string(image)
text = text.encode("ascii", "ignore")
text = text.decode()
context = {
'text': text,
}
return context
我认为我的发布方法有问题,请检查我的代码是否有问题
【问题讨论】:
-
你能粘贴你的 urls.py 吗?
-
好的,添加了 urls.py
标签: python django post methods