Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
from ultralytics import YOLO
|
6 |
+
import easyocr
|
7 |
+
|
8 |
+
# Title of the app
|
9 |
+
st.title("License Plate Recognition 🚗")
|
10 |
+
|
11 |
+
# Load the YOLO model for license plate detection
|
12 |
+
@st.cache_resource
|
13 |
+
def load_yolo_model():
|
14 |
+
model_path = "best.pt" # Replace with your model file
|
15 |
+
model = YOLO(model_path)
|
16 |
+
if torch.cuda.is_available():
|
17 |
+
model.to("cuda")
|
18 |
+
return model
|
19 |
+
|
20 |
+
# Load EasyOCR reader
|
21 |
+
@st.cache_resource
|
22 |
+
def load_easyocr_reader():
|
23 |
+
return easyocr.Reader(['en'], gpu=torch.cuda.is_available())
|
24 |
+
|
25 |
+
# Initialize models
|
26 |
+
yolo_model = load_yolo_model()
|
27 |
+
ocr_reader = load_easyocr_reader()
|
28 |
+
|
29 |
+
# Function to process the uploaded image
|
30 |
+
def process_image(image, confidence_threshold=0.5):
|
31 |
+
# Perform license plate detection
|
32 |
+
results = yolo_model(image, conf=confidence_threshold)
|
33 |
+
annotated_image = cv2.cvtColor(results[0].plot(), cv2.COLOR_BGR2RGB)
|
34 |
+
st.image(annotated_image, caption="Detected License Plate(s)", use_container_width=True)
|
35 |
+
|
36 |
+
# Loop through detections
|
37 |
+
for result in results:
|
38 |
+
boxes = result.boxes.xyxy.cpu().numpy().astype(int)
|
39 |
+
if len(boxes) == 0:
|
40 |
+
st.warning("No license plate detected!")
|
41 |
+
return
|
42 |
+
for i, box in enumerate(boxes):
|
43 |
+
x1, y1, x2, y2 = box
|
44 |
+
cropped_image = image[y1:y2, x1:x2]
|
45 |
+
cropped_image_rgb = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB)
|
46 |
+
st.image(cropped_image_rgb, caption=f"Cropped License Plate {i+1}", use_container_width=True)
|
47 |
+
|
48 |
+
# Perform OCR on the cropped image
|
49 |
+
text_results = ocr_reader.readtext(cropped_image_rgb, detail=0)
|
50 |
+
detected_text = " ".join(text_results)
|
51 |
+
st.write(f"**Extracted Text (Plate {i+1}):** {detected_text}")
|
52 |
+
|
53 |
+
# Sidebar inputs
|
54 |
+
confidence_threshold = st.sidebar.slider("Confidence Threshold", 0.0, 1.0, 0.5, 0.01)
|
55 |
+
uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
|
56 |
+
|
57 |
+
if uploaded_file is not None:
|
58 |
+
# Read the uploaded image
|
59 |
+
image = cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), 1)
|
60 |
+
process_image(image, confidence_threshold)
|
61 |
+
|
62 |
+
st.markdown("---")
|
63 |
+
st.info("**Note:** This application uses EasyOCR for text recognition. Results may vary depending on image quality and lighting conditions.")
|