Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
# app.py
|
| 2 |
-
|
| 3 |
import numpy as np
|
| 4 |
-
np.int = int # patch for PaddleOCRβ
|
| 5 |
|
| 6 |
import cv2, json, tempfile, re
|
| 7 |
import gradio as gr
|
|
@@ -10,32 +9,41 @@ from paddleocr import PaddleOCR
|
|
| 10 |
|
| 11 |
# βββ 1) Load models βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 12 |
yolo = YOLO("models/best.pt")
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
)
|
| 20 |
|
| 21 |
-
# βββ 2)
|
| 22 |
def format_turkish_plate(s: str) -> str:
|
| 23 |
s = re.sub(r'[^A-Z0-9]', '', s.upper())
|
| 24 |
m = re.match(r'^(\d{2})([A-Z]{1,3})(\d{2,4})$', s)
|
| 25 |
return f"{m.group(1)} {m.group(2)} {m.group(3)}" if m else "Unknown"
|
| 26 |
|
| 27 |
-
# βββ
|
| 28 |
def extract_text_score(recs):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
if not recs:
|
| 30 |
return "", 0.0
|
| 31 |
first = recs[0]
|
| 32 |
-
# det=False
|
| 33 |
if isinstance(first, (list,tuple)) and len(first)==2 and isinstance(first[0], str):
|
| 34 |
return first[0], float(first[1])
|
| 35 |
-
# det=True formatΔ±
|
| 36 |
if isinstance(first, list) and first and isinstance(first[0], (list,tuple)):
|
| 37 |
return first[0][0], float(first[0][1])
|
| 38 |
-
# tanΔ±madΔ±
|
| 39 |
return "", 0.0
|
| 40 |
|
| 41 |
# βββ 3) Singleβimage inference βββββββββββββββββββββββββββββββββββββ
|
|
@@ -46,60 +54,70 @@ def run_image(img, conf=0.25):
|
|
| 46 |
for box in res.boxes.xyxy.cpu().numpy().astype(int):
|
| 47 |
x1,y1,x2,y2 = box
|
| 48 |
crop = out[y1:y2, x1:x2]
|
| 49 |
-
if crop.size
|
| 50 |
continue
|
|
|
|
| 51 |
plate_img = cv2.resize(crop, (128,32))
|
| 52 |
try:
|
| 53 |
-
recs = ocr.ocr(plate_img
|
| 54 |
except Exception:
|
| 55 |
recs = []
|
| 56 |
raw, score = extract_text_score(recs)
|
|
|
|
| 57 |
plate = format_turkish_plate(raw)
|
| 58 |
label = f"{plate} ({score:.2f})"
|
|
|
|
| 59 |
cv2.rectangle(out, (x1,y1),(x2,y2), (0,255,0), 2)
|
| 60 |
cv2.putText(out, label, (x1, y1-5),
|
| 61 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
|
|
|
| 62 |
return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s) detected"
|
| 63 |
|
| 64 |
-
# βββ 4) Video inference βββββββββββββββββββββββββββββββββββββββββββ
|
| 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 |
tmp_out = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
|
| 71 |
-
writer
|
| 72 |
-
records = []
|
| 73 |
-
|
| 74 |
while True:
|
| 75 |
ret, frame = cap.read()
|
| 76 |
if not ret: break
|
| 77 |
idx += 1; t = idx/fps
|
|
|
|
| 78 |
res = yolo(frame, conf=conf)[0]
|
| 79 |
for box in res.boxes.xyxy.cpu().numpy().astype(int):
|
| 80 |
x1,y1,x2,y2 = box
|
| 81 |
crop = frame[y1:y2, x1:x2]
|
| 82 |
-
if crop.size
|
| 83 |
continue
|
|
|
|
| 84 |
plate_img = cv2.resize(crop, (128,32))
|
| 85 |
try:
|
| 86 |
-
recs = ocr.ocr(plate_img
|
| 87 |
except Exception:
|
| 88 |
recs = []
|
| 89 |
raw, score = extract_text_score(recs)
|
|
|
|
| 90 |
plate = format_turkish_plate(raw)
|
| 91 |
-
if plate
|
| 92 |
records.append({"time_s":round(t,2),"plate":plate,"conf":round(score,3)})
|
|
|
|
| 93 |
cv2.rectangle(frame, (x1,y1),(x2,y2), (0,255,0), 2)
|
| 94 |
cv2.putText(frame, plate, (x1, y1-5),
|
| 95 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
|
|
|
| 96 |
writer.write(frame)
|
|
|
|
| 97 |
cap.release(); writer.release()
|
| 98 |
with open("output.json","w") as f:
|
| 99 |
json.dump(records, f, indent=2)
|
| 100 |
return tmp_out, "Done"
|
| 101 |
|
| 102 |
-
# βββ 5) Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 103 |
with gr.Blocks() as demo:
|
| 104 |
gr.Markdown("## π License Plate Detection + Recognition")
|
| 105 |
with gr.Row():
|
|
|
|
| 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
|
|
|
|
| 9 |
|
| 10 |
# βββ 1) Load models βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
yolo = YOLO("models/best.pt")
|
| 12 |
+
|
| 13 |
+
ocr = PaddleOCR(
|
| 14 |
+
det=False, # OCR'nin kendi detector'ΓΌnΓΌ kapat
|
| 15 |
+
rec=True, # sadece recognition
|
| 16 |
+
rec_model_dir="models/ocr_model", # iΓ§inde inference.pdmodel / .pdparams / .yml var
|
| 17 |
+
rec_image_shape="3,32,128", # height=32, width=128
|
| 18 |
+
rec_char_dict_path=(
|
| 19 |
+
"/usr/local/lib/python3.10/site-packages/"
|
| 20 |
+
"paddleocr/ppocr/utils/ppocr_keys_v1.txt"
|
| 21 |
+
), # doΔru dict dosyasΔ±
|
| 22 |
+
use_angle_cls=False, # aΓ§Δ± sΔ±nΔ±flandΔ±rmasΔ±nΔ± kapat (opsiyonel)
|
| 23 |
+
use_space_char=True # boΕluk karakterini destekle
|
| 24 |
)
|
| 25 |
|
| 26 |
+
# βββ 2) Plate formatter ββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
def format_turkish_plate(s: str) -> str:
|
| 28 |
s = re.sub(r'[^A-Z0-9]', '', s.upper())
|
| 29 |
m = re.match(r'^(\d{2})([A-Z]{1,3})(\d{2,4})$', s)
|
| 30 |
return f"{m.group(1)} {m.group(2)} {m.group(3)}" if m else "Unknown"
|
| 31 |
|
| 32 |
+
# βββ Helper: OCR Γ§Δ±ktΔ±sΔ±nΔ± normalize et ββββββββββββββββββββββββββββ
|
| 33 |
def extract_text_score(recs):
|
| 34 |
+
"""
|
| 35 |
+
recs (det=False) β [ [text,score], β¦ ]
|
| 36 |
+
recs (det=True) β [ [[text,score],β¦], β¦ ]
|
| 37 |
+
"""
|
| 38 |
if not recs:
|
| 39 |
return "", 0.0
|
| 40 |
first = recs[0]
|
| 41 |
+
# det=False formatΔ±
|
| 42 |
if isinstance(first, (list,tuple)) and len(first)==2 and isinstance(first[0], str):
|
| 43 |
return first[0], float(first[1])
|
| 44 |
+
# det=True formatΔ±
|
| 45 |
if isinstance(first, list) and first and isinstance(first[0], (list,tuple)):
|
| 46 |
return first[0][0], float(first[0][1])
|
|
|
|
| 47 |
return "", 0.0
|
| 48 |
|
| 49 |
# βββ 3) Singleβimage inference βββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 54 |
for box in res.boxes.xyxy.cpu().numpy().astype(int):
|
| 55 |
x1,y1,x2,y2 = box
|
| 56 |
crop = out[y1:y2, x1:x2]
|
| 57 |
+
if crop.size==0:
|
| 58 |
continue
|
| 59 |
+
|
| 60 |
plate_img = cv2.resize(crop, (128,32))
|
| 61 |
try:
|
| 62 |
+
recs = ocr.ocr(plate_img) # artΔ±k det=False, rec_image_shape, dict hep init'de
|
| 63 |
except Exception:
|
| 64 |
recs = []
|
| 65 |
raw, score = extract_text_score(recs)
|
| 66 |
+
|
| 67 |
plate = format_turkish_plate(raw)
|
| 68 |
label = f"{plate} ({score:.2f})"
|
| 69 |
+
|
| 70 |
cv2.rectangle(out, (x1,y1),(x2,y2), (0,255,0), 2)
|
| 71 |
cv2.putText(out, label, (x1, y1-5),
|
| 72 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
| 73 |
+
|
| 74 |
return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s) detected"
|
| 75 |
|
| 76 |
+
# βββ 4) Video inference ββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
def run_video(video_file, conf=0.25):
|
| 78 |
cap = cv2.VideoCapture(video_file)
|
| 79 |
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 80 |
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 81 |
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 82 |
tmp_out = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
|
| 83 |
+
writer = cv2.VideoWriter(tmp_out, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w,h))
|
| 84 |
+
records, idx = [], 0
|
| 85 |
+
|
| 86 |
while True:
|
| 87 |
ret, frame = cap.read()
|
| 88 |
if not ret: break
|
| 89 |
idx += 1; t = idx/fps
|
| 90 |
+
|
| 91 |
res = yolo(frame, conf=conf)[0]
|
| 92 |
for box in res.boxes.xyxy.cpu().numpy().astype(int):
|
| 93 |
x1,y1,x2,y2 = box
|
| 94 |
crop = frame[y1:y2, x1:x2]
|
| 95 |
+
if crop.size==0:
|
| 96 |
continue
|
| 97 |
+
|
| 98 |
plate_img = cv2.resize(crop, (128,32))
|
| 99 |
try:
|
| 100 |
+
recs = ocr.ocr(plate_img)
|
| 101 |
except Exception:
|
| 102 |
recs = []
|
| 103 |
raw, score = extract_text_score(recs)
|
| 104 |
+
|
| 105 |
plate = format_turkish_plate(raw)
|
| 106 |
+
if plate!="Unknown":
|
| 107 |
records.append({"time_s":round(t,2),"plate":plate,"conf":round(score,3)})
|
| 108 |
+
|
| 109 |
cv2.rectangle(frame, (x1,y1),(x2,y2), (0,255,0), 2)
|
| 110 |
cv2.putText(frame, plate, (x1, y1-5),
|
| 111 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
| 112 |
+
|
| 113 |
writer.write(frame)
|
| 114 |
+
|
| 115 |
cap.release(); writer.release()
|
| 116 |
with open("output.json","w") as f:
|
| 117 |
json.dump(records, f, indent=2)
|
| 118 |
return tmp_out, "Done"
|
| 119 |
|
| 120 |
+
# βββ 5) Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 121 |
with gr.Blocks() as demo:
|
| 122 |
gr.Markdown("## π License Plate Detection + Recognition")
|
| 123 |
with gr.Row():
|