DasariHarshitha commited on
Commit
0e8147e
Β·
verified Β·
1 Parent(s): d932be1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -96
app.py CHANGED
@@ -1,96 +1,108 @@
1
- import streamlit as st
2
- import cv2
3
- import numpy as np
4
- import easyocr
5
- from PIL import Image
6
- from tensorflow.keras.models import load_model
7
- from tensorflow.keras.preprocessing import image as keras_image
8
-
9
- # Load model and OCR tools
10
- model = load_model("Vehicle Number Plates.keras")
11
- plate_detector = cv2.CascadeClassifier("haarcascade_license_plate_rus_16stages.xml")
12
- reader = easyocr.Reader(['en'])
13
-
14
- # Plate Detection Function
15
- def detect_and_predict(img_input):
16
- img = np.array(img_input.convert("RGB"))
17
- frame = img.copy()
18
- gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
19
- plates = plate_detector.detectMultiScale(gray, 1.1, 4)
20
-
21
- plate_text = "Not Detected"
22
- confidence = None
23
-
24
- for x, y, w, h in plates:
25
- roi = frame[y:y+h, x:x+w]
26
- try:
27
- test_img = cv2.resize(roi, (200, 200))
28
- test_img = keras_image.img_to_array(test_img) / 255.0
29
- test_img = np.expand_dims(test_img, axis=0)
30
- pred = model.predict(test_img)[0][0]
31
- except Exception as e:
32
- print(f"Prediction error: {e}")
33
- continue
34
-
35
- if pred < 0.5:
36
- result = reader.readtext(roi)
37
- if result:
38
- plate_text = result[0][1]
39
- confidence = result[0][2]
40
- label = f"Plate: {plate_text}"
41
- else:
42
- label = "Plate Detected (No text)"
43
- else:
44
- label = "Plate Not Detected"
45
-
46
- # Draw detection
47
- cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
48
- cv2.putText(frame, label, (x, y - 10),
49
- cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
50
-
51
- return frame, confidence, plate_text
52
-
53
- # Streamlit App UI
54
- st.set_page_config(page_title="License Plate Detection", layout="wide")
55
- st.title("🚘 License Plate Detection App")
56
-
57
- tab1, tab2 = st.tabs(["πŸ“ Upload Image", "πŸ“· Webcam Capture"])
58
-
59
- # Tab 1 - Upload Image
60
- with tab1:
61
- uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
62
- if uploaded_file:
63
- image_input = Image.open(uploaded_file)
64
- st.image(image_input, caption="Uploaded Image", use_container_width=True)
65
-
66
- if st.button("πŸ” Detect from Upload"):
67
- with st.spinner("Processing..."):
68
- result_img, confidence, label = detect_and_predict(image_input)
69
-
70
- st.image(result_img, caption="Detection Result", channels="RGB", use_container_width=True)
71
- if confidence:
72
- st.metric("Confidence", f"{confidence * 100:.2f}%")
73
- st.success(f"Detected Text: {label}")
74
- else:
75
- st.warning("No plate text detected.")
76
-
77
- # Tab 2 - Webcam Input (camera snapshot)
78
- with tab2:
79
- camera_image = st.camera_input("πŸ“· Take a picture using your webcam")
80
- if camera_image:
81
- try:
82
- image_input = Image.open(camera_image)
83
- st.image(image_input, caption="Webcam Snapshot", use_container_width=True)
84
-
85
- with st.spinner("Analyzing..."):
86
- result_img, confidence, label = detect_and_predict(image_input)
87
-
88
- st.image(result_img, caption="Detection Result", channels="RGB", use_container_width=True)
89
- if confidence is not None:
90
- st.metric("Confidence", f"{confidence*100:.2f}%")
91
- st.success(f"Detected Text: {label}")
92
- else:
93
- st.warning("Plate detected but no readable text found.")
94
-
95
- except Exception as e:
96
- st.error(f"❌ Error: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ import numpy as np
4
+ import easyocr
5
+ from PIL import Image
6
+ from tensorflow.keras.models import load_model
7
+ from tensorflow.keras.preprocessing import image as keras_image
8
+
9
+ # Load model and tools
10
+ model = load_model("Vehicle Number Plates.keras")
11
+ plate_detector = cv2.CascadeClassifier("haarcascade_license_plate_rus_16stages.xml")
12
+ reader = easyocr.Reader(['en'])
13
+
14
+ # Detect and predict function
15
+ def detect_and_predict(img_input):
16
+ img = np.array(img_input.convert("RGB"))
17
+ frame = img.copy()
18
+ gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
19
+ plates = plate_detector.detectMultiScale(gray, 1.1, 4)
20
+
21
+ plate_text = "Not Detected"
22
+ confidence = None
23
+
24
+ for x, y, w, h in plates:
25
+ roi = frame[y:y+h, x:x+w]
26
+ try:
27
+ test_img = cv2.resize(roi, (200, 200))
28
+ test_img = keras_image.img_to_array(test_img) / 255.0
29
+ test_img = np.expand_dims(test_img, axis=0)
30
+ pred = model.predict(test_img)[0][0]
31
+ except Exception as e:
32
+ print(f"Prediction error: {e}")
33
+ continue
34
+
35
+ if pred < 0.5:
36
+ result = reader.readtext(roi)
37
+ if result:
38
+ plate_text = result[0][1]
39
+ confidence = result[0][2]
40
+ label = f"Plate: {plate_text}"
41
+ else:
42
+ label = "Plate Detected (No text)"
43
+ else:
44
+ label = "Plate Not Detected"
45
+
46
+ cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
47
+ cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
48
+
49
+ return frame, confidence, plate_text
50
+
51
+ # App Config
52
+ st.set_page_config(page_title="Vehicle Plate Identifier", layout="centered")
53
+
54
+ # Sidebar style
55
+ with st.sidebar:
56
+ st.markdown("## πŸš— License Plate Scanner")
57
+ st.markdown("Upload an image or take a photo to detect and read vehicle number plates using AI and OCR.")
58
+ st.markdown("---")
59
+ st.info("πŸ“Œ Tip: Use clear images with visible plates for best results.")
60
+
61
+ # Title
62
+ st.markdown("<h4 style='text-align: center; color: navy;'>πŸ” AI-Powered Vehicle Plate Detection & OCR</h4>", unsafe_allow_html=True)
63
+
64
+ # Tabs
65
+ tab1, tab2 = st.tabs([
66
+ "πŸ–ΌοΈ **:blue[Upload Vehicle Image]**",
67
+ "πŸ“· **:green[Use Live Webcam]**"
68
+ ])
69
+
70
+ # Tab 1 - Upload
71
+ with tab1:
72
+ st.markdown("#### :blue[Upload an image to detect number plate]", unsafe_allow_html=True)
73
+ uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
74
+ if uploaded_file:
75
+ image_input = Image.open(uploaded_file)
76
+ st.image(image_input, caption="Uploaded Image", width=250)
77
+
78
+ if st.button("πŸ” Detect from Upload"):
79
+ with st.spinner("Processing..."):
80
+ result_img, confidence, label = detect_and_predict(image_input)
81
+
82
+ st.image(result_img, caption="Detection Result", channels="RGB", width=250)
83
+ if confidence:
84
+ st.metric("Confidence", f"{confidence * 100:.2f}%")
85
+ st.success(f"Detected Text: {label}")
86
+ else:
87
+ st.warning("No plate text detected.")
88
+
89
+ # Tab 2 - Webcam
90
+ with tab2:
91
+ st.markdown("#### :green[Capture from your webcam to scan a vehicle plate]", unsafe_allow_html=True)
92
+ camera_image = st.camera_input("πŸ“· Take a picture using your webcam")
93
+ if camera_image:
94
+ try:
95
+ image_input = Image.open(camera_image)
96
+ st.image(image_input, caption="Webcam Snapshot", width=250)
97
+
98
+ with st.spinner("Analyzing..."):
99
+ result_img, confidence, label = detect_and_predict(image_input)
100
+
101
+ st.image(result_img, caption="Detection Result", channels="RGB", width=250)
102
+ if confidence is not None:
103
+ st.metric("Confidence", f"{confidence*100:.2f}%")
104
+ st.success(f"Detected Text: {label}")
105
+ else:
106
+ st.warning("Plate detected but no readable text found.")
107
+ except Exception as e:
108
+ st.error(f"❌ Error: {str(e)}")