File size: 7,689 Bytes
8c42a4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c88f605
 
 
8c42a4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c88f605
 
 
 
8c42a4b
c88f605
8c42a4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c88f605
8c42a4b
 
 
 
 
 
 
 
ac6a917
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c88f605
8c42a4b
c88f605
8c42a4b
ac6a917
c88f605
 
ac6a917
 
 
 
 
 
 
ee29146
c88f605
 
 
 
ee29146
 
c88f605
 
 
8c42a4b
c88f605
 
 
 
 
 
 
ac6a917
 
 
ee29146
 
 
ac6a917
 
 
 
 
c88f605
ee29146
c88f605
ee29146
 
 
 
 
ac6a917
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# import streamlit as st
# import cv2
# import numpy as np
# import easyocr
# from PIL import Image
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image as keras_image

# # Load model and OCR tools
# model = load_model("Vehicle_number_plate_Detection.keras")
# plate_detector = cv2.CascadeClassifier("haarcascade_russian_plate_number.xml")
# reader = easyocr.Reader(['en'])

# # Plate Detection Function
# def detect_and_predict(img_input):
#     img = np.array(img_input.convert("RGB"))
#     frame = img.copy()
#     gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
#     plates = plate_detector.detectMultiScale(gray, 1.1, 4)

#     plate_text = "Not Detected"
#     confidence = None

#     for x, y, w, h in plates:
#         roi = frame[y:y+h, x:x+w]
#         try:
#             test_img = cv2.resize(roi, (200, 200))
#             test_img = keras_image.img_to_array(test_img) / 255.0
#             test_img = np.expand_dims(test_img, axis=0)
#             pred = model.predict(test_img)[0][0]
#         except Exception as e:
#             print(f"Prediction error: {e}")
#             continue

#         if pred < 0.5:
#             result = reader.readtext(roi)
#             if result:
#                 plate_text = result[0][1]
#                 confidence = result[0][2]
#                 label = f"Plate: {plate_text}"
#             else:
#                 label = "Plate Detected (No text)"
#         else:
#             label = "Plate Not Detected"

#         # Draw detection
#         cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
#         cv2.putText(frame, label, (x, y - 10),
#                     cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

#     # Ensure output image is same size as input
#     result_img = Image.fromarray(frame)
#     return result_img, confidence, plate_text

# # Streamlit App UI
# st.set_page_config(page_title="License Plate Detection", layout="wide")
# st.title("🚘 License Plate Detection App")

# tab1, tab2 = st.tabs(["πŸ“ Upload Image", "πŸ“· Webcam Capture"])

# # Tab 1 - Upload Image
# with tab1:
#     col1, col2 = st.columns([1, 2])
#     uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
#     if uploaded_file:
#         image_input = Image.open(uploaded_file)
#         with col1:
#             st.image(image_input, caption="Uploaded Image", use_container_width=True)

#         if st.button("πŸ” Detect from Upload"):
#             with st.spinner("Processing..."):
#                 result_img, confidence, label = detect_and_predict(image_input)

#             with col2:
#                 st.image(result_img, caption="Detection Result", use_container_width=True)
#                 if confidence:
#                     st.metric("Confidence", f"{confidence * 100:.2f}%")
#                     st.success(f"Detected Text: {label}")
#                 else:
#                     st.warning("No plate text detected.")

# # Tab 2 - Webcam Input (camera snapshot)
# with tab2:
#     col1, col2 = st.columns([1, 2])
#     with col1:
#         camera_image = st.camera_input("πŸ“· Take a picture using your webcam")
#     if camera_image:
#         try:
#             image_input = Image.open(camera_image)
#             with st.spinner("Analyzing..."):
#                 result_img, confidence, label = detect_and_predict(image_input)
#             with col2:
#                 st.image(result_img, caption="Detection Result", use_container_width=True)
#                 if confidence is not None:
#                     st.metric("Confidence", f"{confidence*100:.2f}%")
#                     st.success(f"Detected Text: {label}")
#                 else:
#                     st.warning("Plate detected but no readable text found.")
#         except Exception as e:
#             st.error(f"❌ Error: {str(e)}")

import streamlit as st
import cv2
import numpy as np
import easyocr
from PIL import Image
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image as keras_image

# Load model and OCR tools
model = load_model("Vehicle_number_plate_Detection.keras")
plate_detector = cv2.CascadeClassifier("haarcascade_russian_plate_number.xml")
reader = easyocr.Reader(['en'])

# Plate Detection Function
def detect_and_predict(img_input):
    img = np.array(img_input.convert("RGB"))
    frame = img.copy()
    gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    plates = plate_detector.detectMultiScale(gray, 1.1, 4)

    plate_text = "Not Detected"
    confidence = None

    for x, y, w, h in plates:
        roi = frame[y:y+h, x:x+w]
        try:
            test_img = cv2.resize(roi, (200, 200))
            test_img = keras_image.img_to_array(test_img) / 255.0
            test_img = np.expand_dims(test_img, axis=0)
            pred = model.predict(test_img)[0][0]
        except Exception as e:
            print(f"Prediction error: {e}")
            continue

        if pred < 0.5:
            result = reader.readtext(roi)
            if result:
                plate_text = result[0][1]
                confidence = result[0][2]
                label = f"Plate: {plate_text}"
            else:
                label = "Plate Detected (No text)"
        else:
            label = "Plate Not Detected"

        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv2.putText(frame, label, (x, y - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

    # Convert back to PIL and resize to 450x450 for display
    result_img = Image.fromarray(frame)
    result_img = result_img.resize((450, 450))
    return result_img, confidence, plate_text


# Streamlit UI
st.set_page_config(page_title="License Plate Detection", layout="wide")
st.title("🚘 License Plate Detection App")

tab1, tab2 = st.tabs(["πŸ“ Upload Image", "πŸ“· Webcam Capture"])

# Tab 1 - Upload Image
with tab1:
    col1, col2 = st.columns([1, 2])
    with col1:
        uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"], key="uploader")
        if uploaded_file:
            image_input = Image.open(uploaded_file)
            st.image(image_input, caption="Uploaded Image", use_container_width=True)

            if st.button("πŸ” Detect from Upload"):
                with st.spinner("Processing..."):
                    result_img, confidence, label = detect_and_predict(image_input)

                with col2:
                    st.image(result_img, caption="Detection Result (450x450)", use_container_width=False)
                    if confidence:
                        st.metric("Confidence", f"{confidence * 100:.2f}%")
                        st.success(f"Detected Text: {label}")
                    else:
                        st.warning("No plate text detected.")

# Tab 2 - Webcam Input (camera snapshot)
with tab2:
    col1, col2 = st.columns([1, 2])
    with col1:
        camera_image = st.camera_input("πŸ“· Take a picture using your webcam")
    if camera_image:
        try:
            image_input = Image.open(camera_image)
            with st.spinner("Analyzing..."):
                result_img, confidence, label = detect_and_predict(image_input)

            with col2:
                st.image(result_img, caption="Detection Result (450x450)", use_container_width=False)
                if confidence is not None:
                    st.metric("Confidence", f"{confidence*100:.2f}%")
                    st.success(f"Detected Text: {label}")
                else:
                    st.warning("Plate detected but no readable text found.")
        except Exception as e:
            st.error(f"❌ Error: {str(e)}")