muddasser commited on
Commit
f0e8f2a
·
verified ·
1 Parent(s): 5027305

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -48
app.py CHANGED
@@ -6,7 +6,6 @@ import numpy as np
6
  import gradio as gr
7
  import os
8
  import logging
9
- import time
10
 
11
  # Set up logging
12
  logging.basicConfig(level=logging.INFO)
@@ -16,13 +15,13 @@ logger = logging.getLogger(__name__)
16
  os.makedirs(os.getenv('EASYOCR_MODULE_PATH', '/app/.EasyOCR'), exist_ok=True)
17
  os.makedirs(os.getenv('YOLO_CONFIG_DIR', '/app/.config/Ultralytics'), exist_ok=True)
18
 
19
- # Download pretrained ANPR model
20
  ANPR_WEIGHTS = "anpr_yolov8.pt"
21
  if not os.path.exists(ANPR_WEIGHTS):
22
  logger.info(f"Downloading model weights to {ANPR_WEIGHTS}")
23
  os.system(f"wget -O {ANPR_WEIGHTS} https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov8n.pt")
24
 
25
- # Load YOLO ANPR model with error handling
26
  try:
27
  model = YOLO(ANPR_WEIGHTS)
28
  logger.info(f"Successfully loaded YOLO model from {ANPR_WEIGHTS}")
@@ -30,7 +29,7 @@ except Exception as e:
30
  logger.error(f"Error loading YOLO model from {ANPR_WEIGHTS}: {str(e)}")
31
  raise
32
 
33
- # Load OCR reader with specified model storage directory
34
  try:
35
  reader = easyocr.Reader(['en'], model_storage_directory=os.getenv('EASYOCR_MODULE_PATH', '/app/.EasyOCR'))
36
  logger.info("Successfully initialized EasyOCR reader")
@@ -39,74 +38,45 @@ except Exception as e:
39
  raise
40
 
41
  def detect_and_read_plate(image):
42
- start_time = time.time()
43
  logger.info("Starting image processing for license plate detection")
44
-
45
  try:
46
- # Resize image to reduce processing time (optional, adjust as needed)
47
- max_size = 640
48
- h, w = image.shape[:2]
49
- if max(h, w) > max_size:
50
- scale = max_size / max(h, w)
51
- image = cv2.resize(image, (int(w * scale), int(h * scale)))
52
- logger.info(f"Resized image to {image.shape[:2]}")
53
-
54
  detected_texts = []
55
- results = model(image, conf=0.25) # Lower confidence threshold for detection
56
  logger.info(f"YOLO model returned {len(results)} results")
57
 
58
  for result in results:
59
- boxes = result.boxes.xyxy.cpu().numpy() # [x1, y1, x2, y2]
60
- confidences = result.boxes.conf.cpu().numpy()
61
  logger.info(f"Detected {len(boxes)} bounding boxes")
62
-
63
- for box, conf in zip(boxes, confidences):
64
  x1, y1, x2, y2 = map(int, box)
65
- # Skip small or invalid boxes
66
- if (x2 - x1) < 20 or (y2 - y1) < 10:
67
- logger.warning(f"Skipping small box: ({x1}, {y1}, {x2}, {y2})")
68
- continue
69
-
70
  # Crop the detected license plate
71
  plate_img = image[y1:y2, x1:x2]
72
  if plate_img.size == 0:
73
  logger.warning("Empty cropped image, skipping")
74
  continue
75
-
76
- # Run OCR with timeout
77
- try:
78
- logger.info("Running EasyOCR on cropped plate")
79
- ocr_result = reader.readtext(plate_img, timeout=5) # 5-second timeout
80
- if ocr_result:
81
- text = " ".join([res[1] for res in ocr_result if res[2] > 0.3]) # Filter low-confidence OCR
82
- if text.strip():
83
- detected_texts.append(text)
84
- logger.info(f"Detected Plate: {text} (confidence: {conf:.2f})")
85
- else:
86
- logger.info("OCR returned empty or low-confidence text")
87
- else:
88
- logger.info("No text detected by EasyOCR")
89
-
90
  # Draw bounding box
91
  cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
92
- except Exception as e:
93
- logger.warning(f"OCR processing failed: {str(e)}")
94
- continue
95
 
96
- # Prepare output
97
  output_text = "\n".join(detected_texts) if detected_texts else "No license plate detected"
98
- processing_time = time.time() - start_time
99
- logger.info(f"Processing completed in {processing_time:.2f} seconds. Output text: {output_text}")
100
-
101
  return image, output_text
102
  except Exception as e:
103
  logger.error(f"Error during detection: {str(e)}")
104
  return image, f"Error processing image: {str(e)}"
105
 
106
- # Create Gradio interface with progress feedback
107
  with gr.Blocks() as demo:
108
  gr.Markdown("# Automatic Number Plate Recognition (ANPR)")
109
- gr.Markdown("Upload an image of a car to detect and read its license plate. Results may take a few seconds.")
110
 
111
  with gr.Row():
112
  image_input = gr.Image(type="numpy", label="Upload an image of a car")
 
6
  import gradio as gr
7
  import os
8
  import logging
 
9
 
10
  # Set up logging
11
  logging.basicConfig(level=logging.INFO)
 
15
  os.makedirs(os.getenv('EASYOCR_MODULE_PATH', '/app/.EasyOCR'), exist_ok=True)
16
  os.makedirs(os.getenv('YOLO_CONFIG_DIR', '/app/.config/Ultralytics'), exist_ok=True)
17
 
18
+ # Download pretrained model
19
  ANPR_WEIGHTS = "anpr_yolov8.pt"
20
  if not os.path.exists(ANPR_WEIGHTS):
21
  logger.info(f"Downloading model weights to {ANPR_WEIGHTS}")
22
  os.system(f"wget -O {ANPR_WEIGHTS} https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov8n.pt")
23
 
24
+ # Load YOLO model
25
  try:
26
  model = YOLO(ANPR_WEIGHTS)
27
  logger.info(f"Successfully loaded YOLO model from {ANPR_WEIGHTS}")
 
29
  logger.error(f"Error loading YOLO model from {ANPR_WEIGHTS}: {str(e)}")
30
  raise
31
 
32
+ # Load OCR reader
33
  try:
34
  reader = easyocr.Reader(['en'], model_storage_directory=os.getenv('EASYOCR_MODULE_PATH', '/app/.EasyOCR'))
35
  logger.info("Successfully initialized EasyOCR reader")
 
38
  raise
39
 
40
  def detect_and_read_plate(image):
 
41
  logger.info("Starting image processing for license plate detection")
 
42
  try:
 
 
 
 
 
 
 
 
43
  detected_texts = []
44
+ results = model(image) # Use default confidence threshold
45
  logger.info(f"YOLO model returned {len(results)} results")
46
 
47
  for result in results:
48
+ boxes = result.boxes.xyxy.cpu().numpy()
 
49
  logger.info(f"Detected {len(boxes)} bounding boxes")
50
+ for box in boxes:
 
51
  x1, y1, x2, y2 = map(int, box)
 
 
 
 
 
52
  # Crop the detected license plate
53
  plate_img = image[y1:y2, x1:x2]
54
  if plate_img.size == 0:
55
  logger.warning("Empty cropped image, skipping")
56
  continue
57
+ # Run OCR
58
+ logger.info("Running EasyOCR on cropped plate")
59
+ ocr_result = reader.readtext(plate_img)
60
+ if ocr_result:
61
+ text = " ".join([res[1] for res in ocr_result])
62
+ detected_texts.append(text)
63
+ logger.info(f"Detected Plate: {text}")
 
 
 
 
 
 
 
 
64
  # Draw bounding box
65
  cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
66
+ else:
67
+ logger.info("No text detected by EasyOCR")
 
68
 
 
69
  output_text = "\n".join(detected_texts) if detected_texts else "No license plate detected"
70
+ logger.info(f"Output text: {output_text}")
 
 
71
  return image, output_text
72
  except Exception as e:
73
  logger.error(f"Error during detection: {str(e)}")
74
  return image, f"Error processing image: {str(e)}"
75
 
76
+ # Create Gradio interface
77
  with gr.Blocks() as demo:
78
  gr.Markdown("# Automatic Number Plate Recognition (ANPR)")
79
+ gr.Markdown("Upload an image of a car to detect and read its license plate.")
80
 
81
  with gr.Row():
82
  image_input = gr.Image(type="numpy", label="Upload an image of a car")