所以,我想做的是用戶輸入一個 base64 編碼的影像,然后通過 pytesseract OCR 將其轉換為文本。問題是每次我嘗試輸入它時都只重新加載頁面而沒有任何反應。
這是我的 html 片段:
<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>
這是我的 views.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
我認為我的 post 方法有問題,請檢查我的代碼是否有問題
uj5u.com熱心網友回復:
我認為這不是get_context_data()使用 POST 資料的正確方法,因為我認為在 POST 請求中不會呼叫此方法(該方法僅在 GET 請求中使用)。
您是否嘗試過其他方法CreateView?
我建議你試試這個form_valid()方法;這是檔案的另一部分,其中包含一些示例https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-editing/#model-forms
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329442.html
