-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment.py
More file actions
205 lines (164 loc) Β· 6.74 KB
/
Assignment.py
File metadata and controls
205 lines (164 loc) Β· 6.74 KB
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
205
"""
πΈ Real-Time Object Detection with HAAR Cascades (Face, Eyes, Smile, and More)
================================================================================
This script demonstrates real-time object detection using OpenCV's HAAR cascade classifiers.
It highlights how to use pre-trained models to detect multiple types of visual features
such as faces, eyes, and smiles, and can be extended to detect other objects like:
- Full human body
- Upper body
- Cars
- License plates
- Cats, dogs, etc.
The program captures video from the webcam, detects objects in each frame, and overlays
bounding boxes and labels to indicate the detection results.
--------------------------------------------------------------------------------
π― Detection Capabilities:
--------------------------
β
Face Detection:
- Detects human faces using `haarcascade_frontalface_default.xml`
- Draws a green rectangle around each face
- Optionally labels the face
β
Eye Detection:
- Detects eyes within the face region using `haarcascade_eye.xml`
- Draws blue rectangles around eyes
- Can be used for blink or gaze detection extensions
β
Smile Detection:
- Detects smiling within the face region using `haarcascade_smile.xml`
- Draws yellow rectangles around the smile
- Can be used to trigger events like auto-capture
β
Extendable Object Detection:
- Can include other HAAR cascades, such as:
- `haarcascade_fullbody.xml`
- `haarcascade_upperbody.xml`
- `haarcascade_car.xml`
- `haarcascade_russian_plate_number.xml`
- `haarcascade_frontalcatface.xml`
- Simply load the cascade and apply `detectMultiScale()` as shown in the script.
--------------------------------------------------------------------------------
π¦ Requirements:
---------------
- Python 3.x
- OpenCV (`cv2`)
Install OpenCV:
pip install opencv-python
--------------------------------------------------------------------------------
π§ Core Concepts Used:
----------------------
- Grayscale conversion: for faster processing
- `cv2.CascadeClassifier`: for loading XML-based pre-trained models
- `detectMultiScale()`: for object detection at different scales
- Region of Interest (ROI): to restrict detection to specific areas
- Drawing and labeling: with `cv2.rectangle()` and `cv2.putText()`
--------------------------------------------------------------------------------
π οΈ Usage Instructions:
----------------------
1. Ensure the HAAR XML files are correctly placed in your project.
2. Run the script.
3. A window will display the webcam feed with live detections.
4. Press the **'q' key** to quit the program.
--------------------------------------------------------------------------------
π‘ Notes:
--------
- Detection accuracy depends on:
- Lighting conditions
- Camera quality
- Cascade parameters (`scaleFactor`, `minNeighbors`)
- For better results in production apps, consider using:
- DNN models (e.g., OpenCV DNN, MediaPipe, or YOLO)
- Tracking algorithms for object persistence
--------------------------------------------------------------------------------
π¨βπ» Author:
-----------
- Developed as part of an OpenCV exploration project.
- Extend, reuse, or modify freely for learning or custom applications.
"""
import cv2
import tkinter as tk
from tkinter import messagebox
# Path to your HAAR cascades
CASCADE_DIR = "Phase_7/HAAR_CASCADES/"
CASCADE_FILES = {
"Face": "haarcascade_frontalface_default.xml",
"Eyes": "haarcascade_eye.xml",
"Smile": "haarcascade_smile.xml",
"Full Body": "haarcascade_fullbody.xml",
"Upper Body": "haarcascade_upperbody.xml",
"Car": "haarcascade_car.xml",
"License Plate": "haarcascade_russian_plate_number.xml",
"Cat Face": "haarcascade_frontalcatface.xml",
}
class HaarApp:
def __init__(self, root):
self.root = root
self.root.title("HAAR Cascade Detection")
self.root.geometry("400x400")
tk.Label(root, text="Select objects to detect:", font=("Arial", 14)).pack(
pady=10
)
self.vars = {}
for name in CASCADE_FILES:
var = tk.BooleanVar(value=False)
cb = tk.Checkbutton(root, text=name, variable=var, font=("Arial", 12))
cb.pack(anchor="w", padx=20)
self.vars[name] = var
tk.Button(
root,
text="Start Detection",
command=self.start_detection,
font=("Arial", 14),
bg="green",
fg="white",
).pack(pady=20)
def start_detection(self):
selected = [name for name, var in self.vars.items() if var.get()]
if not selected:
messagebox.showwarning(
"No Selection", "Please select at least one detector!"
)
return
cascades = {}
for name in selected:
path = CASCADE_DIR + CASCADE_FILES[name]
cascade = cv2.CascadeClassifier(path)
if cascade.empty():
messagebox.showerror(
"Error", f"Could not load cascade: {CASCADE_FILES[name]}"
)
return
cascades[name] = cascade
cap = cv2.VideoCapture(0)
if not cap.isOpened():
messagebox.showerror("Error", "Could not open webcam.")
return
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
for name, cascade in cascades.items():
# tune parameters depending on cascade type
scale = 1.3
neighbors = 5
min_size = (30, 30)
if name == "Smile":
scale, neighbors = 1.7, 22
elif name == "Eyes":
scale, neighbors = 1.1, 10
rects = cascade.detectMultiScale(
gray, scale, neighbors, minSize=min_size
)
color = (0, 255, 0) if name == "Face" else (255, 0, 0)
for x, y, w, h in rects:
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(
frame, name, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2
)
cv2.imshow("HAAR Detection", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
root = tk.Tk()
app = HaarApp(root)
root.mainloop()