Norakneath commited on
Commit
a598ef7
·
verified ·
1 Parent(s): 8730661

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -16
app.py CHANGED
@@ -3,39 +3,77 @@ import torch
3
  from ultralytics import YOLO
4
  from PIL import Image, ImageDraw
5
 
6
- # Load YOLO model (Ensure best.pt is in the same directory)
7
  YOLO_MODEL_PATH = "best.pt"
8
  model = YOLO(YOLO_MODEL_PATH, task='detect').to("cpu") # Force CPU usage
9
 
10
- def detect_text(image):
11
- """ Runs YOLOv8 detection on the input image and returns bounding box results. """
12
- image = Image.fromarray(image) # Convert NumPy array to PIL Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # Run YOLO detection
15
- results = model.predict(image, conf=0.3, iou=0.4, device="cpu")
 
 
 
 
 
16
  detected_boxes = results[0].boxes.xyxy.tolist()
 
 
 
 
17
 
18
  # Draw bounding boxes
19
  image_with_boxes = image.copy()
20
  draw = ImageDraw.Draw(image_with_boxes)
21
-
22
- for box in detected_boxes:
23
- x1, y1, x2, y2 = map(int, box)
24
- draw.rectangle([x1, y1, x2, y2], outline="red", width=2) # Draw bounding box
25
- draw.text((x1, y1 - 10), "Text", fill="red") # Label each box
26
 
27
  return image_with_boxes
28
 
29
  # Define Gradio interface
30
  with gr.Blocks() as iface:
31
- gr.Markdown("# Text Detection with YOLOv8")
32
- gr.Markdown("## Upload an image and detect text regions using YOLO")
33
 
34
  with gr.Tab("Upload Image"):
35
- gr.Markdown("Upload an image, and the YOLO model will detect text in the image.")
36
  image_input = gr.Image(type="numpy", label="Upload an image")
37
- image_output = gr.Image(type="pil", label="Detected text")
38
- image_input.upload(detect_text, inputs=image_input, outputs=image_output)
 
39
 
40
  # Launch Gradio interface
41
  iface.launch()
 
3
  from ultralytics import YOLO
4
  from PIL import Image, ImageDraw
5
 
6
+ # Load YOLO model for line detection
7
  YOLO_MODEL_PATH = "best.pt"
8
  model = YOLO(YOLO_MODEL_PATH, task='detect').to("cpu") # Force CPU usage
9
 
10
+ def merge_boxes_into_lines(boxes, y_threshold=20):
11
+ """
12
+ Merge bounding boxes that are close together in the y-axis (same line).
13
+ Args:
14
+ boxes: List of bounding boxes [x1, y1, x2, y2]
15
+ y_threshold: Max distance between words to consider as the same line
16
+ Returns:
17
+ List of merged line bounding boxes without overlap
18
+ """
19
+ if len(boxes) == 0:
20
+ return []
21
+
22
+ # Sort boxes by y1 (top position)
23
+ boxes = sorted(boxes, key=lambda b: b[1])
24
+
25
+ merged_lines = []
26
+ current_line = list(boxes[0])
27
+
28
+ for i in range(1, len(boxes)):
29
+ x1, y1, x2, y2 = boxes[i]
30
+
31
+ # Merge boxes that are close in the y-axis
32
+ if abs(y1 - current_line[1]) < y_threshold:
33
+ current_line[0] = min(current_line[0], x1) # Expand left boundary
34
+ current_line[2] = max(current_line[2], x2) # Expand right boundary
35
+ current_line[3] = max(current_line[3], y2) # Expand bottom boundary
36
+ else:
37
+ merged_lines.append(current_line)
38
+ current_line = list(boxes[i])
39
+
40
+ merged_lines.append(current_line)
41
+ return merged_lines
42
 
43
+ def detect_lines(image):
44
+ """Runs YOLOv8 detection on the input image to detect lines."""
45
+ image = Image.fromarray(image) # Convert NumPy array to PIL Image
46
+
47
+ # Run YOLO detection with confidence threshold 0.2
48
+ results = model.predict(image, conf=0.2, iou=0.4, device="cpu")
49
+
50
  detected_boxes = results[0].boxes.xyxy.tolist()
51
+ detected_boxes = [list(map(int, box)) for box in detected_boxes] # Convert to integer
52
+
53
+ # Merge detected bounding boxes into line-level boxes
54
+ merged_boxes = merge_boxes_into_lines(detected_boxes)
55
 
56
  # Draw bounding boxes
57
  image_with_boxes = image.copy()
58
  draw = ImageDraw.Draw(image_with_boxes)
59
+
60
+ for idx, (x1, y1, x2, y2) in enumerate(merged_boxes):
61
+ draw.rectangle([x1, y1, x2, y2], outline="blue", width=2)
62
+ draw.text((x1, y1 - 10), f"Line {idx}", fill="blue")
 
63
 
64
  return image_with_boxes
65
 
66
  # Define Gradio interface
67
  with gr.Blocks() as iface:
68
+ gr.Markdown("# Line Detection with YOLOv8")
69
+ gr.Markdown("## Upload an image to detect text lines using YOLOv8")
70
 
71
  with gr.Tab("Upload Image"):
72
+ gr.Markdown("Upload an image, and the YOLO model will detect lines of text.")
73
  image_input = gr.Image(type="numpy", label="Upload an image")
74
+ image_output = gr.Image(type="pil", label="Detected lines")
75
+
76
+ image_input.upload(detect_lines, inputs=image_input, outputs=image_output)
77
 
78
  # Launch Gradio interface
79
  iface.launch()