APIMONSTER commited on
Commit
847a398
Β·
verified Β·
1 Parent(s): 6589a14

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -47
app.py CHANGED
@@ -1,75 +1,119 @@
1
  # app.py
2
  import cv2, json, tempfile, re
3
  import numpy as np
 
4
  np.int = int
5
  import gradio as gr
6
  from ultralytics import YOLO
7
  from paddleocr import PaddleOCR
8
 
9
- # 1) Load models
10
  yolo = YOLO("models/best.pt")
11
  ocr = PaddleOCR(
12
- det=False, # turn off detection
13
- rec=True, # enable recognition only
14
  rec_model_dir="models/ocr_model",
15
- cls=False, # no angle‐classification
16
  )
17
 
18
- # 2) Turkish plate formatter
19
  def format_turkish_plate(s: str) -> str:
20
  m = re.match(r"^(\d{2})([A-Z]{1,3})(\d{2,4})$", s.replace(" ",""))
21
  return f"{m[1]} {m[2]} {m[3]}" if m else "Unknown"
22
 
23
- # 3) Single‐image pipeline
24
  def run_image(img, conf=0.25):
 
25
  bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
26
  res = yolo(bgr, conf=conf)[0]
27
  out = bgr.copy()
28
- for box,score in zip(res.boxes.xyxy.cpu().numpy(), res.boxes.conf.cpu().numpy()):
 
 
 
29
  x1,y1,x2,y2 = box.astype(int)
30
  roi = out[y1:y2, x1:x2]
31
- if roi.size==0: continue
32
- plate_img = cv2.resize(roi,(128,32))
33
- rec = ocr.ocr(plate_img, cls=True)[0]
34
- text = "".join(w[1][0] for w in rec) if rec else ""
35
- label= format_turkish_plate(text)
36
- cv2.rectangle(out,(x1,y1),(x2,y2),(0,255,0),2)
37
- cv2.putText(out,f"{label} {score:.2f}",(x1,y1-5),
38
- cv2.FONT_HERSHEY_SIMPLEX,0.6,(0,255,0),2)
39
- return cv2.cvtColor(out,cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s)"
40
-
41
- # 4) Video pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def run_video(video_file, conf=0.25):
43
- cap = cv2.VideoCapture(video_file)
44
- fps = cap.get(cv2.CAP_PROP_FPS)
45
- w,h = int(cap.get(3)), int(cap.get(4))
46
- outfp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
47
- writer= cv2.VideoWriter(outfp, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w,h))
48
- records=[]
49
- idx=0
 
 
 
 
 
50
  while True:
51
- ret,frame=cap.read()
52
- if not ret: break
53
- idx+=1; t=idx/fps
54
- res=yolo(frame,conf=conf)[0]
55
- for (x1,y1,x2,y2) in res.boxes.xyxy.cpu().numpy().astype(int):
56
- roi=frame[y1:y2,x1:x2]
57
- if roi.size==0: continue
58
- plate_img=cv2.resize(roi,(128,32))
59
- rec=ocr.ocr(plate_img, cls=True)[0]
60
- text="".join(w[1][0] for w in rec) if rec else ""
61
- label=format_turkish_plate(text)
62
- score=min(w[1][1] for w in rec) if rec else 0.0
63
- if label!="Unknown":
64
- records.append({"time_s":round(t,2),"plate":label,"conf":round(score,3)})
65
- cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
66
- cv2.putText(frame,label,(x1,y1-5),cv2.FONT_HERSHEY_SIMPLEX,0.6,(0,255,0),2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  writer.write(frame)
68
- cap.release(); writer.release()
69
- with open("output.json","w") as f: json.dump(records, f, indent=2)
70
- return outfp
71
 
72
- # 5) Gradio UI
 
 
 
 
 
 
73
  with gr.Blocks() as demo:
74
  gr.Markdown("## πŸš— License Plate Detection + Recognition")
75
  with gr.Row():
@@ -83,7 +127,9 @@ with gr.Blocks() as demo:
83
  img_out = gr.Image(type="numpy", label="Annotated Image")
84
  vid_out = gr.Video(label="Annotated Video")
85
  txt_out = gr.Textbox(label="Status / JSON Path")
86
- btn1.click(run_image, [img_in,slider],[img_out,txt_out])
87
- btn2.click(run_video, [vid_in,slider],[vid_out,txt_out])
 
 
88
  if __name__=="__main__":
89
  demo.launch()
 
1
  # app.py
2
  import cv2, json, tempfile, re
3
  import numpy as np
4
+ # restore the old alias so that `np.int` still works in older code
5
  np.int = int
6
  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, # built-in detection kapalΔ±
14
+ rec=True, # sadece recognition
15
  rec_model_dir="models/ocr_model",
16
+ cls=False, # angle-classification kapalΔ±
17
  )
18
 
19
+ # ─── 2) Turkish plate formatter ────────────────────────────────────
20
  def format_turkish_plate(s: str) -> str:
21
  m = re.match(r"^(\d{2})([A-Z]{1,3})(\d{2,4})$", s.replace(" ",""))
22
  return f"{m[1]} {m[2]} {m[3]}" if m else "Unknown"
23
 
24
+ # ─── 3) Single-image pipeline ─────────────────────────────────────
25
  def run_image(img, conf=0.25):
26
+ # BGR ← RGB
27
  bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
28
  res = yolo(bgr, conf=conf)[0]
29
  out = bgr.copy()
30
+ count = 0
31
+
32
+ for box,score in zip(res.boxes.xyxy.cpu().numpy(),
33
+ res.boxes.conf.cpu().numpy()):
34
  x1,y1,x2,y2 = box.astype(int)
35
  roi = out[y1:y2, x1:x2]
36
+ if roi.size == 0:
37
+ continue
38
+
39
+ # Resize for OCR
40
+ plate_img = cv2.resize(roi, (128,32))
41
+ recs = ocr.ocr(plate_img, cls=True)
42
+ if not recs or not recs[0]:
43
+ # BOŞ sonuç: OCR hiç text tespit edemedi demektir.
44
+ continue
45
+
46
+ rec = recs[0]
47
+ text = "".join(w[1][0] for w in rec)
48
+ formatted = format_turkish_plate(text)
49
+ score_rec = min(w[1][1] for w in rec)
50
+
51
+ label = f"{formatted} {score_rec:.2f}"
52
+ cv2.rectangle(out, (x1,y1), (x2,y2), (0,255,0), 2)
53
+ cv2.putText(out, label, (x1, y1-6),
54
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
55
+ count += 1
56
+
57
+ return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{count} plate(s) detected"
58
+
59
+ # ─── 4) Video pipeline ───────────────────────────────────────────
60
  def run_video(video_file, conf=0.25):
61
+ cap = cv2.VideoCapture(video_file)
62
+ fps = cap.get(cv2.CAP_PROP_FPS)
63
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
64
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
65
+
66
+ out_fp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
67
+ writer = cv2.VideoWriter(out_fp,
68
+ cv2.VideoWriter_fourcc(*"mp4v"),
69
+ fps, (w,h))
70
+
71
+ records = []
72
+ idx = 0
73
  while True:
74
+ ret, frame = cap.read()
75
+ if not ret:
76
+ break
77
+ idx += 1
78
+ t = idx / fps
79
+
80
+ res = yolo(frame, conf=conf)[0]
81
+ for box in res.boxes.xyxy.cpu().numpy().astype(int):
82
+ x1,y1,x2,y2 = box
83
+ roi = frame[y1:y2, x1:x2]
84
+ if roi.size == 0:
85
+ continue
86
+
87
+ plate_img = cv2.resize(roi, (128,32))
88
+ recs = ocr.ocr(plate_img, cls=True)
89
+ if not recs or not recs[0]:
90
+ continue
91
+
92
+ rec = recs[0]
93
+ text = "".join(w[1][0] for w in rec)
94
+ formatted = format_turkish_plate(text)
95
+ score_rec = min(w[1][1] for w in rec)
96
+
97
+ records.append({
98
+ "time_s": round(t,2),
99
+ "plate": formatted,
100
+ "conf": round(score_rec,3)
101
+ })
102
+
103
+ cv2.rectangle(frame, (x1,y1), (x2,y2), (0,255,0), 2)
104
+ cv2.putText(frame, f"{formatted} {score_rec:.2f}",
105
+ (x1, y1-6),
106
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
107
+
108
  writer.write(frame)
 
 
 
109
 
110
+ cap.release()
111
+ writer.release()
112
+ with open("output.json", "w") as f:
113
+ json.dump(records, f, indent=2)
114
+ return out_fp
115
+
116
+ # ─── 5) Gradio UI ────────────────────────────────────────────────
117
  with gr.Blocks() as demo:
118
  gr.Markdown("## πŸš— License Plate Detection + Recognition")
119
  with gr.Row():
 
127
  img_out = gr.Image(type="numpy", label="Annotated Image")
128
  vid_out = gr.Video(label="Annotated Video")
129
  txt_out = gr.Textbox(label="Status / JSON Path")
130
+
131
+ btn1.click(run_image, [img_in, slider], [img_out, txt_out])
132
+ btn2.click(run_video, [vid_in, slider], [vid_out, txt_out])
133
+
134
  if __name__=="__main__":
135
  demo.launch()