0% found this document useful (0 votes)
16 views

To create a more advanced driver drowsiness detection system using a Raspberry Pi 5 with an IP camera

Uploaded by

krishedu07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

To create a more advanced driver drowsiness detection system using a Raspberry Pi 5 with an IP camera

Uploaded by

krishedu07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

To create a more advanced driver drowsiness detection system using a Raspberry Pi 5 with an IP

camera, we can enhance the features by incorporating the following:

1. Real-time Alert System: Use sound alerts and visual indicators.

2. Data Logging: Store timestamps and drowsiness events in a log file.

3. Web Dashboard: Create a more comprehensive web dashboard for monitoring.

4. Use of Machine Learning: Implement a more robust model for detecting drowsiness.

5. User Authentication: Secure the web app with basic user authentication.

Overview of the Advanced System

 Components Required:

 Raspberry Pi 5

 IP Camera (ensure it supports RTSP or HTTP streaming)

 Python with OpenCV, Flask, and other libraries

 A speaker or buzzer for alerts

 A smartphone or computer to view the app

 A database (e.g., SQLite) for logging events

Step 1: Install Required Libraries

Make sure you have the following libraries installed:

bash

VerifyOpen In EditorEditCopy code

1sudo apt update

2sudo apt install python3-opencv python3-flask python3-sqlite3 python3-pip

3pip3 install dlib numpy flask-login

Step 2: Create the Database for Logging Events

Create a SQLite database to log drowsiness events. You can create a file named database.py:

python

VerifyOpen In EditorEditCopy code

1import sqlite3

3def create_db():

4 conn = sqlite3.connect('drowsiness_log.db')

5 c = conn.cursor()
6 c.execute('''

7 CREATE TABLE IF NOT EXISTS logs (

8 id INTEGER PRIMARY KEY AUTOINCREMENT,

9 timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,

10 status TEXT

11 )

12 ''')

13 conn.commit()

14 conn.close()

15

16if __name__ == "__main__":

17 create_db()

Run this script once to create the database:

bash

VerifyOpen In EditorEditCopy code

1python3 database.py

Step 3: Advanced Drowsiness Detection Code

Here’s an enhanced version of the drowsiness detection system:

python

VerifyOpen In EditorEditCopy code

1import cv2

2import dlib

3import numpy as np

4from flask import Flask, Response, render_template, redirect, url_for, request, session

5import sqlite3

6import time

7import os

8from threading import Thread

9from playsound import playsound

10

11app = Flask(__name__)
12app.secret_key = 'your_secret_key' # Change this to a random secret key

13

14# Load the pre-trained face detector and shape predictor

15detector = dlib.get_frontal_face_detector()

16predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

17

18# Drowsiness detection parameters

19EYE_AR_THRESH = 0.25

20EYE_AR_CONSEC_FRAMES = 48

21COUNTER = 0

22ALERTED = False

23

24def eye_aspect_ratio(eye):

25 A = np.linalg.norm(eye[1] - eye[5])

26 B = np.linalg.norm(eye[2] - eye[4])

27 C = np.linalg.norm(eye[0] - eye[3])

28 ear = (A + B) / (2.0 * C)

29 return ear

30

31def log_event(status):

32 conn = sqlite3.connect('drowsiness_log.db')

33 c = conn.cursor()

34 c.execute("INSERT INTO logs (status) VALUES (?)", (status,))

35 conn.commit()

36 conn.close()

37

38def detect_drowsiness(frame):

39 global COUNTER, ALERTED

40 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

41 faces = detector(gray)

42
43 for face in faces:

44 landmarks = predictor(gray, face)

45 left_eye = np.array([(landmarks.part(36).x, landmarks.part(36).y),

46 (landmarks.part(37).x, landmarks.part(37).y),

47 (landmarks.part(38).x, landmarks.part(38).y),

48 (landmarks.part(39).x, landmarks.part(39).y),

49 (landmarks.part(40).x, landmarks.part(40).y),

50 (landmarks.part(41).x, landmarks.part(41).y)])

51

52 right_eye = np.array([(landmarks.part(42).x, landmarks.part(42).y),

53 (landmarks.part(43).x, landmarks.part(43).y),

54 (landmarks.part(44).x, landmarks.part(44).y),

55 (landmarks.part(45).x, landmarks.part(45).y),

56 (landmarks.part(46).x, landmarks.part(46).y),

57 (landmarks.part(47).x, landmarks.part(47).y)])

58

59 left_ear = eye_aspect_ratio(left_eye)

60 right_ear = eye_aspect_ratio(right_eye)

61 ear = (left_ear + right_ear) / 2.0

62

63 if ear < EYE_AR_THRESH:

64 COUNTER += 1

65 if COUNTER >= EYE_AR_CONSEC_FRAMES:

66 if not ALERTED:

67 ALERTED = True

68 log_event("DROWSY")

69 Thread(target=playsound, args=("alarm.mp3",)).start()

70 cv2.putText(frame, "DROWSY", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

71 else:

72 COUNTER = 0

73 ALERTED = False
74

75 return frame

76

77def generate_frames():

78 camera_url = "http://<IP_CAMERA_URL>/video"

79 camera = cv2.VideoCapture(camera_url)

80

81 while True:

82 success, frame = camera.read()

83 if not success:

84 break

85 frame = detect_drowsiness(frame)

86 ret, buffer = cv2.imencode('.jpg', frame)

87 frame = buffer.tobytes()

88 yield (b'--frame\r\n'

89 b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

90

[email protected]('/video_feed')

92def video_feed():

93 return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

94

[email protected]('/login', methods=['GET', 'POST'])

96def login():

97 if request.method == 'POST':

98 username = request.form['username']

99 password = request.form['password']

100 if username == 'admin' and password == 'password': # Change these to your desired
credentials

101 session['logged_in'] = True

102 return redirect(url_for('index'))

103 else:
104 return render_template('login.html', error='Invalid credentials')

105 return render_template('login.html')

106

[email protected]('/logout')

108def logout():

109 session.pop('logged_in', None)

110 return redirect(url_for('login'))

111

[email protected]('/')

113def index():

114 if 'logged_in' in session:

115 return render_template('index.html')

116 else:

117 return redirect(url_for('login'))

118

119if __name__ == "__main__":

120 app.run(host='0.0.0.0', port=5000)

Step 4: Create the Web Dashboard

Create a templates directory and add the following HTML files:

login.html:

html

VerifyOpen In EditorEditRunCopy code

1<!DOCTYPE html>

2<html>

3<head>

4 <title>Login</title>

5</head>

6<body>

7 <h1>Login</h1>

8 <form action="" method="post">

9 <label for="username">Username:</label><br>
10 <input type="text" id="username" name="username"><br>

11 <label for="password">Password:</label><br>

12 <input type="password" id="password" name="password"><br>

13 <input type="submit" value="Login">

14 </form>

15 {% if error %}

16 <p style="color: red;">{{ error }}</p>

17 {% endif %}

18</body>

19</html>

index.html:

html

VerifyOpen In EditorEditRunCopy code

1<!DOCTYPE html>

2<html>

3<head>

4 <title>Drowsiness Detection System</title>

5</head>

6<body>

7 <h1>Drowsiness Detection System</h1>

8 <img src="{{ url_for('video_feed') }}" width="640" height="480">

9</body>

10</html>

Step 5: Run the Application

Run the Python script using python3 your_script.py. Open a web browser and navigate
to http://<Raspberry_Pi_IP>:5000 to access the web dashboard. Log in with your credentials, and
you'll see the video feed with drowsiness detection.

Remember to replace <IP_CAMERA_URL> with your IP camera's URL and <Raspberry_Pi_IP> with
your Raspberry Pi's IP address. Also, update the username and password in the login function to
your desired credentials.

/<Raspberry_Pi_IP> how to find it


How can I find my raspberry pi ip address? : r/raspberry_pi - Reddit

reddit

How to find the current IP address? - Raspberry Pi Forums

forums.raspberrypi

Finding the IP Address of your Raspberry Pi - Pi My Life Up

pimylifeup

To find IP address of Rpi3 without Monitor connected into it

forums.raspberrypi

To find the IP address of a Raspberry Pi, you can use several methods depending on whether you
have physical access to the device or if you need to find it remotely. Here are the most common
methods:

Method 1: Using the Terminal on the Raspberry Pi

If you have physical access to your Raspberry Pi and can use a monitor and keyboard, follow these
steps:

1. Open the Terminal: You can do this by clicking on the terminal icon or pressing Ctrl + Alt + T.

2. Run the Command: Type the following command and press Enter:

bash

VerifyOpen In EditorEditCopy code

1hostname -I

 This command will display the IP address(es) assigned to your Raspberry Pi.

Method 2: Checking the Router's Device List

If you don't have direct access to the Raspberry Pi, you can find its IP address through your router:

1. Access Your Router: Open a web browser and enter your router's IP address
(commonly http://192.168.1.1 or http://192.168.0.1).

2. Log In: Enter your router's username and password.

3. Find Connected Devices: Look for a section that lists connected devices. This may be labeled
as "Device List," "Connected Devices," or something similar.
4. Identify the Raspberry Pi: Look for a device named "raspberrypi" or similar in the list. The
corresponding IP address will be displayed next to it.

Method 3: Using the ping Command

If you have access to another device on the same network, you can try to ping the Raspberry Pi:

1. Open a Terminal or Command Prompt on another device (Windows, macOS, or Linux).

2. Ping the Hostname: Use the following command:

bash

VerifyOpen In EditorEditCopy code

1ping raspberrypi.local

 If the Raspberry Pi responds, the IP address will be shown in the output.

Method 4: Using nmap Tool

If the above methods do not work, you can use the nmap tool to scan your network:

1. Install nmap: If you don't have it installed, you can install it using:

 Linux:

bash

VerifyOpen In EditorEditCopy code

1sudo apt install nmap

 Windows: Download from nmap's official site.

2. Find Your Subnet: Determine your local IP address and subnet. For example, if your IP
is 192.168.1.45, your subnet is 192.168.1.0/24.

3. Run the nmap Command:

bash

VerifyOpen In EditorEditCopy code

1nmap -sn 192.168.1.0/24

 This command will scan the subnet and list all devices connected, including your
Raspberry Pi.

Conclusion

By using any of these methods, you should be able to find the IP address of your Raspberry Pi.
Choose the method that best suits your situation based on your access to the device and network.

You might also like