eoeooe commited on
Commit
400665c
·
verified ·
1 Parent(s): 259b92e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -7
app.py CHANGED
@@ -11,11 +11,23 @@ def ocr_with_boxes(image):
11
  # แปลงจาก PIL → OpenCV
12
  img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
13
 
14
- # config ไทย + อังกฤษ
15
- custom_config = r'-l tha+eng --oem 3 --psm 6'
16
-
 
 
 
 
 
 
 
 
 
 
 
 
17
  # OCR with bounding boxes
18
- data = pytesseract.image_to_data(img, config=custom_config, output_type=Output.DICT)
19
 
20
  totalBox = len(data['text'])
21
  lines = defaultdict(list)
@@ -37,7 +49,7 @@ def ocr_with_boxes(image):
37
  extracted_texts = [" ".join(words) for _, words in sorted(lines.items())]
38
  final_text = "\n".join(extracted_texts)
39
 
40
- # 🔧 แก้เว้นวรรคภาษาไทยตรงนี้เลย
41
  final_text = re.sub(r'([\u0E00-\u0E7F])\s+([\u0E00-\u0E7F])', r'\1\2', final_text)
42
 
43
  # แปลงกลับเป็น PIL
@@ -51,8 +63,8 @@ demo = gr.Interface(
51
  fn=ocr_with_boxes,
52
  inputs=gr.Image(type="pil", label="อัปโหลดภาพ"),
53
  outputs=[gr.Image(label="ผลลัพธ์พร้อมกรอบข้อความ"), gr.Textbox(label="ข้อความ OCR")],
54
- title="OCR ไทย + อังกฤษ (Tesseract + Fix Spacing)",
55
- description="อัปโหลดภาพ ระบบจะ OCR ไทย+อังกฤษ วาดกรอบ และแก้เว้นวรรคภาษาไทยอัตโนมัติ"
56
  )
57
 
58
  if __name__ == "__main__":
 
11
  # แปลงจาก PIL → OpenCV
12
  img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
13
 
14
+ # --- Preprocessing เพื่อให้ OCR อ่านโลโก้แม่นขึ้น ---
15
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # เป็น grayscale
16
+ gray = cv2.adaptiveThreshold(
17
+ gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
18
+ cv2.THRESH_BINARY, 11, 2
19
+ )
20
+ kernel = np.ones((2, 2), np.uint8)
21
+ gray = cv2.dilate(gray, kernel, iterations=1)
22
+ gray = cv2.erode(gray, kernel, iterations=1)
23
+
24
+ # --- Tesseract config ---
25
+ # oem 3 = LSTM neural net, psm 6 = assume a block of text
26
+ # whitelist สำหรับตัวอักษรอังกฤษ + ตัวเลข
27
+ custom_config = r'-l tha+eng --oem 3 --psm 6 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
28
+
29
  # OCR with bounding boxes
30
+ data = pytesseract.image_to_data(gray, config=custom_config, output_type=Output.DICT)
31
 
32
  totalBox = len(data['text'])
33
  lines = defaultdict(list)
 
49
  extracted_texts = [" ".join(words) for _, words in sorted(lines.items())]
50
  final_text = "\n".join(extracted_texts)
51
 
52
+ # 🔧 แก้เว้นวรรคภาษาไทย
53
  final_text = re.sub(r'([\u0E00-\u0E7F])\s+([\u0E00-\u0E7F])', r'\1\2', final_text)
54
 
55
  # แปลงกลับเป็น PIL
 
63
  fn=ocr_with_boxes,
64
  inputs=gr.Image(type="pil", label="อัปโหลดภาพ"),
65
  outputs=[gr.Image(label="ผลลัพธ์พร้อมกรอบข้อความ"), gr.Textbox(label="ข้อความ OCR")],
66
+ title="OCR ไทย + อังกฤษ (Tesseract + Logo Fix)",
67
+ description="อัปโหลดภาพ ระบบจะ OCR ไทย+อังกฤษ วาดกรอบ และแก้เว้นวรรคภาษาไทยอัตโนมัติ พร้อมปรับให้โลโก้ภาษาอังกฤษอ่านแม่นขึ้น"
68
  )
69
 
70
  if __name__ == "__main__":