APIMONSTER commited on
Commit
50d8b94
Β·
verified Β·
1 Parent(s): 089fa45

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -52
app.py CHANGED
@@ -7,68 +7,51 @@ import gradio as gr
7
  from ultralytics import YOLO
8
  from paddleocr import PaddleOCR
9
 
10
- # ─── 1) Load models ───────────────────────────────────────────────
11
  yolo = YOLO("models/best.pt")
12
  ocr = PaddleOCR(
13
- det=False, # <<< OCR’nin kendi detector’ınΔ± tamamen kapatΔ±yoruz
14
- rec=True,
15
  text_recognition_model_dir="models/ocr_model",
16
  use_textline_orientation=False,
17
  lang="en"
18
  )
19
 
20
- # ─── 2) Turkish plate formatter ────────────────────────────────────
21
  def format_turkish_plate(s: str) -> str:
22
  s = re.sub(r'[^A-Z0-9]', '', s.upper())
23
  m = re.match(r'^(\d{2})([A-Z]{1,3})(\d{2,4})$', s)
24
  return f"{m.group(1)} {m.group(2)} {m.group(3)}" if m else "Unknown"
25
 
26
- # ─── 3) OCR Γ§Δ±ktΔ±sΔ±nΔ± normalize et ─────────────────────────────────
27
- def extract_text_score(recs):
28
- if not recs:
29
- return "", 0.0
30
- first = recs[0]
31
- # format: [text, score]
32
- if isinstance(first, (list,tuple)) and len(first)==2 and isinstance(first[0], str):
33
- text, score = first[0], first[1]
34
- # format: [[...], (text,score)] veya [[...], [text,score]]
35
- elif isinstance(first, (list,tuple)) and len(first)==2 and isinstance(first[1], (list,tuple)):
36
- text, score = first[1][0], first[1][1]
37
- else:
38
- return "", 0.0
39
- try:
40
- score = float(score)
41
- except:
42
- score = 0.0
43
- return text, score
44
-
45
- # ─── 4) Single‐image inference ─────────────────────────────────────
46
  def run_image(img, conf=0.25):
47
  bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
48
  res = yolo(bgr, conf=conf)[0]
49
  out = bgr.copy()
50
 
51
- for box in res.boxes.xyxy.cpu().numpy().astype(int):
52
- x1,y1,x2,y2 = box
 
53
  crop = out[y1:y2, x1:x2]
54
- if crop.size == 0:
55
- continue
56
 
57
  plate_img = cv2.resize(crop, (128,32))
58
- # <<< mutlaka det=False veriyoruz
59
- recs = ocr.ocr(plate_img, det=False, cls=False)
 
 
 
 
60
 
61
- raw, score = extract_text_score(recs)
62
  plate = format_turkish_plate(raw)
63
- label = f"{plate} ({score:.2f})"
64
 
65
  cv2.rectangle(out, (x1,y1),(x2,y2), (0,255,0), 2)
66
- cv2.putText(out, label, (x1, y1-5),
67
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
68
 
69
  return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s) detected"
70
 
71
- # ─── 5) Video inference ────────────────────────────────────────────
72
  def run_video(video_file, conf=0.25):
73
  cap = cv2.VideoCapture(video_file)
74
  fps = cap.get(cv2.CAP_PROP_FPS)
@@ -86,21 +69,21 @@ def run_video(video_file, conf=0.25):
86
  res = yolo(frame, conf=conf)[0]
87
  for (x1,y1,x2,y2) in res.boxes.xyxy.cpu().numpy().astype(int):
88
  crop = frame[y1:y2, x1:x2]
89
- if crop.size == 0:
90
- continue
91
-
92
  plate_img = cv2.resize(crop, (128,32))
93
- recs = ocr.ocr(plate_img, det=False, cls=False)
 
 
 
 
 
94
 
95
- raw, score = extract_text_score(recs)
96
  plate = format_turkish_plate(raw)
97
  if plate != "Unknown":
98
- records.append({"time_s":round(t,2),
99
- "plate":plate,
100
- "conf":round(score,3)})
101
 
102
  cv2.rectangle(frame, (x1,y1),(x2,y2), (0,255,0), 2)
103
- cv2.putText(frame, plate, (x1, y1-5),
104
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
105
 
106
  writer.write(frame)
@@ -108,25 +91,25 @@ def run_video(video_file, conf=0.25):
108
  cap.release(); writer.release()
109
  with open("output.json","w") as f:
110
  json.dump(records, f, indent=2)
111
- return outfp, "Done"
112
 
113
- # ─── 6) Gradio UI ─────────���────────────────────────────────────────
114
  with gr.Blocks() as demo:
115
  gr.Markdown("## πŸš— License Plate Detection + Recognition")
116
  with gr.Row():
117
  with gr.Column():
118
- img_in = gr.Image(type="numpy", label="Upload Image")
119
- vid_in = gr.File(label="Upload Video (.mp4)")
120
- conf = gr.Slider(0,1,0.25,0.01, label="YOLO Confidence")
121
  b1 = gr.Button("Run Image")
122
  b2 = gr.Button("Run Video")
123
  with gr.Column():
124
- img_out = gr.Image(type="numpy", label="Annotated Image")
125
- vid_out = gr.Video(label="Annotated Video")
126
- status = gr.Textbox(label="Status / JSON Path")
127
 
128
  b1.click(run_image, [img_in,conf], [img_out,status])
129
  b2.click(run_video, [vid_in,conf], [vid_out,status])
130
 
131
  if __name__=="__main__":
132
- demo.launch()
 
7
  from ultralytics import YOLO
8
  from paddleocr import PaddleOCR
9
 
10
+ # 1) Load models
11
  yolo = YOLO("models/best.pt")
12
  ocr = PaddleOCR(
13
+ text_detection_model_dir=None,
 
14
  text_recognition_model_dir="models/ocr_model",
15
  use_textline_orientation=False,
16
  lang="en"
17
  )
18
 
19
+ # 2) Turkish plate formatter
20
  def format_turkish_plate(s: str) -> str:
21
  s = re.sub(r'[^A-Z0-9]', '', s.upper())
22
  m = re.match(r'^(\d{2})([A-Z]{1,3})(\d{2,4})$', s)
23
  return f"{m.group(1)} {m.group(2)} {m.group(3)}" if m else "Unknown"
24
 
25
+ # 3) Single‐image inference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  def run_image(img, conf=0.25):
27
  bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
28
  res = yolo(bgr, conf=conf)[0]
29
  out = bgr.copy()
30
 
31
+ for box, yolo_score in zip(res.boxes.xyxy.cpu().numpy(),
32
+ res.boxes.conf.cpu().numpy()):
33
+ x1,y1,x2,y2 = box.astype(int)
34
  crop = out[y1:y2, x1:x2]
35
+ if crop.size==0: continue
 
36
 
37
  plate_img = cv2.resize(crop, (128,32))
38
+ recs = ocr.ocr(plate_img, cls=False)
39
+
40
+ if recs and recs[0]:
41
+ _, (raw, ocr_score) = recs[0]
42
+ else:
43
+ raw, ocr_score = "", 0.0
44
 
 
45
  plate = format_turkish_plate(raw)
46
+ label = f"{plate} ({ocr_score:.2f})"
47
 
48
  cv2.rectangle(out, (x1,y1),(x2,y2), (0,255,0), 2)
49
+ cv2.putText(out, label, (x1,y1-5),
50
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
51
 
52
  return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s) detected"
53
 
54
+ # 4) Video inference (same pattern)
55
  def run_video(video_file, conf=0.25):
56
  cap = cv2.VideoCapture(video_file)
57
  fps = cap.get(cv2.CAP_PROP_FPS)
 
69
  res = yolo(frame, conf=conf)[0]
70
  for (x1,y1,x2,y2) in res.boxes.xyxy.cpu().numpy().astype(int):
71
  crop = frame[y1:y2, x1:x2]
72
+ if crop.size==0: continue
 
 
73
  plate_img = cv2.resize(crop, (128,32))
74
+ recs = ocr.ocr(plate_img, cls=False)
75
+
76
+ if recs and recs[0]:
77
+ _, (raw, ocr_score) = recs[0]
78
+ else:
79
+ raw, ocr_score = "", 0.0
80
 
 
81
  plate = format_turkish_plate(raw)
82
  if plate != "Unknown":
83
+ records.append({"time_s":round(t,2), "plate":plate, "conf":round(ocr_score,3)})
 
 
84
 
85
  cv2.rectangle(frame, (x1,y1),(x2,y2), (0,255,0), 2)
86
+ cv2.putText(frame, plate, (x1,y1-5),
87
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
88
 
89
  writer.write(frame)
 
91
  cap.release(); writer.release()
92
  with open("output.json","w") as f:
93
  json.dump(records, f, indent=2)
94
+ return outfp
95
 
96
+ # 5) Gradio UI
97
  with gr.Blocks() as demo:
98
  gr.Markdown("## πŸš— License Plate Detection + Recognition")
99
  with gr.Row():
100
  with gr.Column():
101
+ img_in = gr.Image(type="numpy")
102
+ vid_in = gr.File(label="Video (.mp4)")
103
+ conf = gr.Slider(0,1,0.25,0.01)
104
  b1 = gr.Button("Run Image")
105
  b2 = gr.Button("Run Video")
106
  with gr.Column():
107
+ img_out = gr.Image(type="numpy")
108
+ vid_out = gr.Video()
109
+ status = gr.Textbox()
110
 
111
  b1.click(run_image, [img_in,conf], [img_out,status])
112
  b2.click(run_video, [vid_in,conf], [vid_out,status])
113
 
114
  if __name__=="__main__":
115
+ demo.launch()