APIMONSTER commited on
Commit
8f59c1f
Β·
verified Β·
1 Parent(s): a0e95d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -41
app.py CHANGED
@@ -1,86 +1,106 @@
1
  # app.py
 
2
  import numpy as np
3
- np.int = int # patch for PaddleOCR’s old np.int calls
4
 
5
- import cv2, json, tempfile, re
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
- 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)
58
- w,h = int(cap.get(3)), int(cap.get(4))
 
59
  outfp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
60
  writer = cv2.VideoWriter(outfp, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w,h))
61
- records, idx = [], 0
 
62
 
63
  while True:
64
  ret, frame = cap.read()
65
  if not ret: break
66
- idx += 1
67
- t = idx / fps
68
 
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),
@@ -91,25 +111,26 @@ def run_video(video_file, conf=0.25):
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()
 
1
  # app.py
2
+
3
  import numpy as np
4
+ np.int = int # PaddleOCR’nin eski np.int kullanΔ±m yamasΔ±
5
 
6
+ import cv2, json, tempfile, re, 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
+
13
+ ocr = PaddleOCR(
14
+ det=False, # OCR’nin kendi tespitini kapatΔ±yoruz
15
+ rec=True, # sadece okuma
16
+ rec_model_dir="models/ocr_model",
17
+ rec_image_shape="3,32,128", # inference.yml ile birebir aynΔ±
18
+ cls=True, # aΓ§Δ± sΔ±nΔ±flandΔ±rΔ±cΔ±sΔ±
19
+ use_angle_cls=True, # v2.x flag
20
+ use_space_char=True # boşluk okumasına izin
21
  )
22
 
23
+ # ─── 2) Plaka formatlayΔ±cΔ± ─────────────────────────────────────────
24
  def format_turkish_plate(s: str) -> str:
25
  s = re.sub(r'[^A-Z0-9]', '', s.upper())
26
  m = re.match(r'^(\d{2})([A-Z]{1,3})(\d{2,4})$', s)
27
  return f"{m.group(1)} {m.group(2)} {m.group(3)}" if m else "Unknown"
28
 
29
+ # ─── 3) GΓΆrΓΌntΓΌ pipeline ────────────────────────────────────────────
30
  def run_image(img, conf=0.25):
31
  bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
32
  res = yolo(bgr, conf=conf)[0]
33
  out = bgr.copy()
34
 
35
+ for box, _ in zip(res.boxes.xyxy.cpu().numpy(),
36
+ res.boxes.conf.cpu().numpy()):
37
  x1,y1,x2,y2 = box.astype(int)
38
  crop = out[y1:y2, x1:x2]
39
+ if crop.size == 0:
40
+ continue
41
+
42
+ plate_img = cv2.resize(crop, (128, 32))
43
 
44
+ # burada dahili tespiti kapattΔ±k
45
+ try:
46
+ recs = ocr.ocr(plate_img, det=False, cls=True)
47
+ except Exception:
48
+ recs = []
49
 
50
  if recs and recs[0]:
51
+ raw_text, ocr_score = recs[0][1][0], recs[0][1][1]
52
  else:
53
+ raw_text, ocr_score = "", 0.0
54
 
55
+ plate = format_turkish_plate(raw_text)
56
  label = f"{plate} ({ocr_score:.2f})"
57
 
58
  cv2.rectangle(out, (x1,y1),(x2,y2), (0,255,0), 2)
59
+ cv2.putText(out, label, (x1, y1-5),
60
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
61
 
62
  return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s) detected"
63
 
64
+ # ─── 4) Video pipeline ─────────────────────────────────────────────
65
  def run_video(video_file, conf=0.25):
66
  cap = cv2.VideoCapture(video_file)
67
  fps = cap.get(cv2.CAP_PROP_FPS)
68
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
69
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
70
  outfp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
71
  writer = cv2.VideoWriter(outfp, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w,h))
72
+ records = []
73
+ idx = 0
74
 
75
  while True:
76
  ret, frame = cap.read()
77
  if not ret: break
78
+ idx += 1; t = idx/fps
 
79
 
80
  res = yolo(frame, conf=conf)[0]
81
  for (x1,y1,x2,y2) in res.boxes.xyxy.cpu().numpy().astype(int):
82
  crop = frame[y1:y2, x1:x2]
83
+ if crop.size == 0:
84
+ continue
85
+
86
  plate_img = cv2.resize(crop, (128,32))
87
+ try:
88
+ recs = ocr.ocr(plate_img, det=False, cls=True)
89
+ except Exception:
90
+ recs = []
91
 
92
  if recs and recs[0]:
93
+ raw_text, ocr_score = recs[0][1][0], recs[0][1][1]
94
  else:
95
+ raw_text, ocr_score = "", 0.0
96
 
97
+ plate = format_turkish_plate(raw_text)
98
  if plate != "Unknown":
99
+ records.append({
100
+ "time_s": round(t,2),
101
+ "plate": plate,
102
+ "conf": round(ocr_score,3)
103
+ })
104
 
105
  cv2.rectangle(frame, (x1,y1),(x2,y2), (0,255,0), 2)
106
  cv2.putText(frame, plate, (x1,y1-5),
 
111
  cap.release(); writer.release()
112
  with open("output.json","w") as f:
113
  json.dump(records, f, indent=2)
114
+ return outfp, "Done"
115
 
116
+ # ─── 5) Gradio UI ──────────────────────────────────────────────────
117
  with gr.Blocks() as demo:
118
  gr.Markdown("## πŸš— License Plate Detection + Recognition")
119
+
120
  with gr.Row():
121
  with gr.Column():
122
+ img_in = gr.Image(type="numpy", label="Upload Image")
123
+ vid_in = gr.File(label="Upload Video (.mp4)")
124
+ conf = gr.Slider(0,1,0.25,0.01, label="YOLO Confidence")
125
  b1 = gr.Button("Run Image")
126
  b2 = gr.Button("Run Video")
127
  with gr.Column():
128
+ img_out = gr.Image(type="numpy", label="Annotated Image")
129
+ vid_out = gr.Video(label="Annotated Video")
130
+ status = gr.Textbox(label="Status / JSON Path")
131
 
132
  b1.click(run_image, [img_in,conf], [img_out,status])
133
  b2.click(run_video, [vid_in,conf], [vid_out,status])
134
 
135
+ if __name__ == "__main__":
136
+ demo.launch()