-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_datasetCreation.py
More file actions
74 lines (60 loc) · 2.06 KB
/
1_datasetCreation.py
File metadata and controls
74 lines (60 loc) · 2.06 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
import imutils
import time
import cv2
import csv
import os
# Load the cascade file
cascade = 'haarcascade_frontalface_default.xml'
detector = cv2.CascadeClassifier(cascade)
# Get user input
Name = input("Enter your Name: ")
Roll_Number = input("Enter your Roll Number: ")
# Create a directory for the dataset if it doesn't exist
dataset = 'dataset'
sub_data = Name
path = os.path.join(dataset, sub_data)
if not os.path.isdir(path):
os.makedirs(path)
print(f"Directory created for {sub_data}")
# Save user info in CSV
info = [Name, Roll_Number]
with open('student.csv', 'a', newline='') as csvFile:
write = csv.writer(csvFile)
write.writerow(info)
print("Starting video stream...")
cam = cv2.VideoCapture(0) # Use 0 if 1 doesn't work
# Check if camera opened successfully
if not cam.isOpened():
print("Error: Could not open video stream.")
cam.release()
cv2.destroyAllWindows()
else:
time.sleep(2.0)
total = 0
while total < 50:
print(f"Capturing image {total + 1} of 50")
ret, frame = cam.read()
# If frame not captured, exit
if not ret:
print("Error: Failed to capture frame.")
break
# Resize the frame and convert it to grayscale
img = imutils.resize(frame, width=400)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = detector.detectMultiScale(
gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
)
# Draw rectangles around detected faces and save images
for (x, y, w, h) in rects:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
p = os.path.join(path, f"{str(total).zfill(5)}.png")
cv2.imwrite(p, img)
total += 1
# Show the video stream with rectangles around detected faces
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
# Release camera and close all windows
cam.release()
cv2.destroyAllWindows()