Sourudra commited on
Commit
87160fd
·
verified ·
1 Parent(s): 4a00297

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -59
app.py CHANGED
@@ -1,66 +1,135 @@
1
  import streamlit as st
2
- import numpy as np
3
- import torch
4
  from ultralytics import YOLO
5
- import easyocr
 
6
  from PIL import Image
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
- # Convert the PIL image to a numpy array
32
- image_np = np.array(image)
33
-
34
- # Perform license plate detection
35
- results = yolo_model(image_np, conf=confidence_threshold)
36
- annotated_image = Image.fromarray(results[0].plot())
37
- st.image(annotated_image, caption="Detected License Plate(s)", use_container_width=True)
38
-
39
- # Loop through detections
40
- for result in results:
41
- boxes = result.boxes.xyxy.cpu().numpy().astype(int)
42
- if len(boxes) == 0:
43
- st.warning("No license plate detected!")
44
- return
45
- for i, box in enumerate(boxes):
46
- x1, y1, x2, y2 = box
47
- cropped_image = image_np[y1:y2, x1:x2]
48
- cropped_image_pil = Image.fromarray(cropped_image)
49
- st.image(cropped_image_pil, caption=f"Cropped License Plate {i+1}", use_container_width=True)
50
-
51
- # Perform OCR on the cropped image
52
- text_results = ocr_reader.readtext(np.array(cropped_image_pil), detail=0)
53
- detected_text = " ".join(text_results)
54
- st.write(f"**Extracted Text (Plate {i+1}):** {detected_text}")
55
-
56
- # Sidebar inputs
57
- confidence_threshold = st.sidebar.slider("Confidence Threshold", 0.0, 1.0, 0.5, 0.01)
58
- uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
 
 
 
 
 
 
 
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  if uploaded_file is not None:
61
- # Open the uploaded file as a PIL image
62
- image = Image.open(uploaded_file)
63
- process_image(image, confidence_threshold)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- st.markdown("---")
66
- st.info("**Note:** This application uses EasyOCR for text recognition. Results may vary depending on image quality and lighting conditions.")
 
 
1
  import streamlit as st
 
 
2
  from ultralytics import YOLO
3
+ import numpy as np
4
+ import cv2
5
  from PIL import Image
6
 
7
+ # Model labels
8
+ model1Labels = {0: 'single_number_plate', 1: 'double_number_plate'}
9
+
10
+ model2Labels = {
11
+ 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C',
12
+ 13: 'D', 14: 'E', 15: 'F', 16: 'G', 17: 'H', 18: 'I', 19: 'J', 20: 'K', 21: 'L', 22: 'M', 23: 'N', 24: 'O',
13
+ 25: 'P', 26: 'Q', 27: 'R', 28: 'S', 29: 'T', 30: 'U', 31: 'V', 32: 'W', 33: 'X', 34: 'Y', 35: 'Z'
14
+ }
15
+
16
+ # Load models
17
+ model = YOLO("models/LP-detection.pt")
18
+ model2 = YOLO("models/Charcter-LP.pt")
19
+
20
+ def prediction(image):
21
+ result = model.predict(source=image, conf=0.5)
22
+ boxes = result[0].boxes
23
+ height = boxes.xywh
24
+ crd = boxes.data
25
+
26
+ n = len(crd)
27
+ lp_number = []
28
+ img_lp_final = None
29
+
30
+ for i in range(n):
31
+ ht = int(height[i][3])
32
+ c = int(crd[i][5])
33
+
34
+ xmin = int(crd[i][0])
35
+ ymin = int(crd[i][1])
36
+ xmax = int(crd[i][2])
37
+ ymax = int(crd[i][3])
38
+
39
+ img_lp = image[ymin:ymax, xmin:xmax]
40
+ img_lp_final = img_lp.copy() # Store the cropped image for display
41
+ cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
42
+
43
+ h = np.median(ht)
44
+
45
+ # Second Model Prediction
46
+ result2 = model2.predict(source=img_lp, conf=0.25)
47
+ boxes_ocr = result2[0].boxes
48
+ data2 = boxes_ocr.data
49
+
50
+ n2 = len(data2)
51
+ xaxis0, xaxis11, xaxis12 = [], [], []
52
+ label0, label11, label12 = [], [], []
53
+ numberPlate = ""
54
+
55
+ if c == 0: # Single line license plate
56
+ for i in range(n2):
57
+ x = int(data2[i][2])
58
+ xaxis0.append(x)
59
+ l = int(data2[i][5])
60
+ label0.append(l)
61
+
62
+ # Sort characters by x-axis for single line
63
+ sorted_labels = [label0[i] for i in np.argsort(xaxis0)]
64
+ numberPlate = ''.join([model2Labels.get(l) for l in sorted_labels])
65
+ lp_number.append(numberPlate)
66
 
67
+ elif c == 1: # Double line license plate
68
+ for i in range(n2):
69
+ x = int(data2[i][0])
70
+ y = int(data2[i][3])
71
+ l = int(data2[i][5])
72
+ if y < (h / 2):
73
+ xaxis11.append(x)
74
+ label11.append(l)
75
+ else:
76
+ xaxis12.append(x)
77
+ label12.append(l)
78
+
79
+ # Sort characters by x-axis for double line (upper and lower separately)
80
+ sorted_labels11 = [label11[i] for i in np.argsort(xaxis11)]
81
+ sorted_labels12 = [label12[i] for i in np.argsort(xaxis12)]
82
+ numberPlate = ''.join([model2Labels.get(l) for l in sorted_labels11 + sorted_labels12])
83
+ lp_number.append(numberPlate)
84
+
85
+ return lp_number, img_lp_final
86
+
87
+ st.title('License Plate Recognition 🚗')
88
+ st.header('Upload an image of a license plate to get the License number.')
89
+
90
+ # Define example images (update with actual paths)
91
+ example_images = {
92
+ "Car ": "test/audiR8V10.jpg",
93
+ "Car 2": "test/c7.jpg",
94
+ "Car 3": "test/c4.jpg",
95
+ "CCTV B/W": "test/cctv img plate.jpg",
96
+ "Bike": "test/BikeNumberPlate.jpg",
97
+ "Bus": "test/bus.jpg",
98
+ }
99
+
100
+ # File uploader
101
+ uploaded_file = st.file_uploader("Choose an image...", type="jpg")
102
+
103
+
104
+
105
+ c1, c2 = st.columns(2)
106
+ for name, path in example_images.items():
107
+ with c1:
108
+ example_img = Image.open(path)
109
+
110
+ image = None
111
  if uploaded_file is not None:
112
+ image = np.array(Image.open(uploaded_file))
113
+ else:
114
+ st.header("Or choose an example image from below dropdown:")
115
+ selected_example = st.selectbox("", list(example_images.keys()))
116
+ if selected_example:
117
+ image = np.array(Image.open(example_images[selected_example]))
118
+
119
+ if image is not None:
120
+ c1, c2, c3 = st.columns(3)
121
+
122
+ with c1:
123
+ st.image(image, caption='Uploaded Image', use_column_width=True)
124
+
125
+ license_plate_text, img_lp = prediction(image)
126
+
127
+ with c2:
128
+ if img_lp is not None:
129
+ st.image(img_lp, caption='Cropped License Plate', use_column_width=True)
130
+ else:
131
+ st.write('No License Plate Detected')
132
 
133
+ with c3:
134
+ st.success(', '.join(license_plate_text))
135
+ st.write('License Plate Text')