Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,40 +1,45 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
import cv2
|
|
|
|
|
|
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
-
from paddleocr import PaddleOCR, draw_ocr
|
| 5 |
from PIL import Image
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# OCR
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
# ดึงกล่อง + ข้อความ
|
| 18 |
-
boxes = [line[0] for line in result[0]]
|
| 19 |
-
texts = [line[1][0] for line in result[0]]
|
| 20 |
-
scores = [line[1][1] for line in result[0]]
|
| 21 |
-
|
| 22 |
-
# วาดกรอบ
|
| 23 |
-
im_show = draw_ocr(img, boxes, texts, scores, font_path='th_font.ttf')
|
| 24 |
-
im_show = Image.fromarray(im_show)
|
| 25 |
-
|
| 26 |
-
# รวมข้อความ
|
| 27 |
-
extracted_text = "\n".join(texts)
|
| 28 |
-
|
| 29 |
-
return im_show, extracted_text
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
inputs=gr.Image(type="pil"),
|
| 34 |
-
outputs=
|
| 35 |
-
title="
|
| 36 |
-
description="
|
| 37 |
)
|
| 38 |
|
| 39 |
-
|
| 40 |
-
demo.launch()
|
|
|
|
|
|
|
| 1 |
import cv2
|
| 2 |
+
import pytesseract
|
| 3 |
+
from pytesseract import Output
|
| 4 |
+
import gradio as gr
|
| 5 |
import numpy as np
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
|
| 8 |
+
def preprocess_image(img):
|
| 9 |
+
"""Preprocessing เพื่อให้ OCR ไทย+อังกฤษ แม่นขึ้น"""
|
| 10 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 11 |
+
|
| 12 |
+
# ลด noise
|
| 13 |
+
gray = cv2.medianBlur(gray, 3)
|
| 14 |
+
|
| 15 |
+
# Thresholding (adaptive) เพื่อให้ text ชัด
|
| 16 |
+
thresh = cv2.adaptiveThreshold(
|
| 17 |
+
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
| 18 |
+
cv2.THRESH_BINARY, 11, 2
|
| 19 |
+
)
|
| 20 |
+
return thresh
|
| 21 |
+
|
| 22 |
+
def ocr_image(img_pil):
|
| 23 |
+
# แปลง PIL -> OpenCV
|
| 24 |
+
img = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)
|
| 25 |
+
|
| 26 |
+
# Preprocessing
|
| 27 |
+
processed_img = preprocess_image(img)
|
| 28 |
+
|
| 29 |
+
# Config สำหรับไทย+อังกฤษ
|
| 30 |
+
custom_config = r'-l tha+eng --oem 3 --psm 6 -c language_model_ngram_space_delimited_language=1'
|
| 31 |
+
|
| 32 |
# OCR
|
| 33 |
+
text = pytesseract.image_to_string(processed_img, config=custom_config)
|
| 34 |
+
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# Gradio interface
|
| 37 |
+
iface = gr.Interface(
|
| 38 |
+
fn=ocr_image,
|
| 39 |
inputs=gr.Image(type="pil"),
|
| 40 |
+
outputs="text",
|
| 41 |
+
title="OCR ไทย + อังกฤษ (Preprocessed)",
|
| 42 |
+
description="อัปโหลดรูปเพื่ออ่านข้อความภาษาไทยและอังกฤษ พร้อมปรับภาพให้แม่นยำขึ้น"
|
| 43 |
)
|
| 44 |
|
| 45 |
+
iface.launch()
|
|
|