Sourudra commited on
Commit
129b2b3
·
verified ·
1 Parent(s): f27d4d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -80
app.py CHANGED
@@ -3,6 +3,7 @@ import cv2
3
  import numpy as np
4
  import easyocr
5
  from ultralytics import YOLO
 
6
 
7
  # Title of the app
8
  st.title("License Plate Recognition System🚗")
@@ -28,101 +29,58 @@ def process_image(image, confidence_threshold=0.5):
28
  # Perform license plate detection
29
  results = yolo_model(image, conf=confidence_threshold)
30
  annotated_image = cv2.cvtColor(results[0].plot(), cv2.COLOR_BGR2RGB)
31
- st.image(annotated_image, caption="Detected License Plate(s)", use_container_width=True)
32
-
33
  # Loop through detections and perform OCR
 
 
 
34
  for result in results:
35
  boxes = result.boxes.xyxy.cpu().numpy().astype(int)
36
  if len(boxes) == 0:
37
  st.warning("No license plate detected!")
38
- return
39
  for i, box in enumerate(boxes):
40
  x1, y1, x2, y2 = box
41
  cropped_image = image[y1:y2, x1:x2]
42
  cropped_image_rgb = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB)
43
- st.image(cropped_image_rgb, caption=f"Cropped License Plate {i+1}", use_container_width=True)
44
-
45
  # Perform OCR on the cropped image
46
  text_results = ocr_reader.readtext(cropped_image_rgb, detail=0)
47
  detected_text = " ".join(text_results)
48
- st.write(f"**Extracted Text (Plate {i+1}):** {detected_text}")
49
- st.write(f"**Confidence Score:** {result.boxes.conf.cpu().numpy()[i]:.2f}")
50
-
51
- # Function to process video and detect license plates
52
- def process_video(video_path, confidence_threshold=0.5, output_path="output_video.mp4"):
53
- # Open the video file
54
- cap = cv2.VideoCapture(video_path)
55
-
56
- # Get video frame dimensions
57
- frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
58
- frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
59
-
60
- # Create VideoWriter object to save the output video
61
- fourcc = cv2.VideoWriter_fourcc(*"mp4v") # Codec for mp4
62
- out = cv2.VideoWriter(output_path, fourcc, 20.0, (frame_width, frame_height)) # 20 FPS
63
-
64
- if not cap.isOpened():
65
- st.error("Error opening video stream or file")
66
- return
67
-
68
- while cap.isOpened():
69
- ret, frame = cap.read()
70
- if not ret:
71
- break
72
 
73
- results = yolo_model(frame, conf=confidence_threshold)
74
- annotated_frame = cv2.cvtColor(results[0].plot(), cv2.COLOR_BGR2RGB)
75
-
76
- # Loop through detections and perform OCR
77
- for result in results:
78
- boxes = result.boxes.xyxy.cpu().numpy().astype(int)
79
- for i, box in enumerate(boxes):
80
- x1, y1, x2, y2 = box
81
- cropped_plate = frame[y1:y2, x1:x2]
82
- cropped_rgb = cv2.cvtColor(cropped_plate, cv2.COLOR_BGR2RGB)
83
-
84
- # Perform OCR on the cropped image
85
- text_results = ocr_reader.readtext(cropped_rgb, detail=0)
86
- detected_text = " ".join(text_results)
87
-
88
- # Optionally add detected text on the annotated frame
89
- cv2.putText(annotated_frame, detected_text, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
90
-
91
- # Write the annotated frame to the output video
92
- out.write(cv2.cvtColor(annotated_frame, cv2.COLOR_RGB2BGR))
93
-
94
- cap.release()
95
- out.release()
96
-
97
- st.success(f"Video processing complete. Output video saved to {output_path}")
98
-
99
- # Provide a download link for the processed video
100
- with open(output_path, "rb") as f:
101
- st.download_button(label="Download Processed Video", data=f, file_name=output_path)
102
 
103
  # Sidebar input for file upload
104
- uploaded_file = st.file_uploader("Upload an Image or Video", type=["mp4", "avi", "mov", "jpg", "jpeg", "png"])
105
 
106
  if uploaded_file is not None:
107
- # Check if it's an image or video
108
- file_type = uploaded_file.type
109
-
110
- if file_type.startswith("image"):
111
- # Read and process the image
112
- image = cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), 1)
113
- confidence_threshold = st.sidebar.slider("Confidence Threshold", 0.0, 1.0, 0.5, 0.01)
114
- process_image(image, confidence_threshold)
115
-
116
- elif file_type.startswith("video"):
117
- # Save the uploaded video to a temporary file
118
- video_bytes = uploaded_file.read()
119
- video_path = "/tmp/uploaded_video.mp4"
120
- with open(video_path, "wb") as f:
121
- f.write(video_bytes)
122
-
123
- # Process the video and save the output
124
- output_path = "/tmp/output_video.mp4"
125
- process_video(video_path, confidence_threshold=0.5, output_path=output_path)
126
-
 
 
 
 
 
 
127
  st.markdown("---")
128
- st.info("This application uses Fine Tuned YOLOv8 for detection and EasyOCR for text recognition.")
 
3
  import numpy as np
4
  import easyocr
5
  from ultralytics import YOLO
6
+ from PIL import Image
7
 
8
  # Title of the app
9
  st.title("License Plate Recognition System🚗")
 
29
  # Perform license plate detection
30
  results = yolo_model(image, conf=confidence_threshold)
31
  annotated_image = cv2.cvtColor(results[0].plot(), cv2.COLOR_BGR2RGB)
32
+
 
33
  # Loop through detections and perform OCR
34
+ license_plate_text = []
35
+ cropped_images = []
36
+
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
+ cropped_images.append(cropped_image_rgb)
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
+ license_plate_text.append(detected_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ return license_plate_text, cropped_images
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  # Sidebar input for file upload
56
+ uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
57
 
58
  if uploaded_file is not None:
59
+ # Read and process the image
60
+ image = np.array(Image.open(uploaded_file))
61
+ confidence_threshold = st.sidebar.slider("Confidence Threshold", 0.0, 1.0, 0.5, 0.01)
62
+
63
+ # Create three columns to display the images side by side
64
+ c1, c2, c3 = st.columns(3)
65
+
66
+ with c1:
67
+ st.image(image, caption='Uploaded Image', use_container_width=True)
68
+
69
+ license_plate_text, cropped_images = process_image(image, confidence_threshold)
70
+
71
+ with c2:
72
+ if cropped_images:
73
+ for i, cropped_image in enumerate(cropped_images):
74
+ st.image(cropped_image, caption=f'Cropped License Plate {i+1}', use_container_width=True)
75
+ else:
76
+ st.write('No License Plate Detected')
77
+
78
+ with c3:
79
+ if license_plate_text:
80
+ st.success(', '.join(license_plate_text))
81
+ st.write('License Plate Text')
82
+ else:
83
+ st.write('No text detected')
84
+
85
  st.markdown("---")
86
+ st.info("This application uses Fine Tuned YOLOv8 for detection and EasyOCR for text recognition.")