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

Code 1

This Python code defines a function to capture images from a webcam and save them to a folder. The function takes a person's name and number of images as parameters, initializes the webcam, detects faces in each frame, saves face images to a folder, and closes the webcam when complete.

Uploaded by

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

Code 1

This Python code defines a function to capture images from a webcam and save them to a folder. The function takes a person's name and number of images as parameters, initializes the webcam, detects faces in each frame, saves face images to a folder, and closes the webcam when complete.

Uploaded by

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

import cv2

import os

def capture_images(person_name, image_count):


# Initialize the webcam or camera module
cap = cv2.VideoCapture(0)

# Create a folder for the person's images if it doesn't exist


folder_path = f'images/{person_name}'
os.makedirs(folder_path, exist_ok=True)

# Load the Haar cascade for face detection


face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')

# Capture images
count = 0
while count < image_count:
# Capture frame-by-frame
ret, frame = cap.read()

# Convert the frame to grayscale for face detection


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

# Detect faces in the grayscale frame


faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3,
minNeighbors=5)

for (x, y, w, h) in faces:


# Draw rectangle around the face
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

# Save the face image to the folder


face_image = os.path.join(folder_path,
f'{person_name}_{count}.jpg')
cv2.imwrite(face_image, frame[y:y + h, x:x + w])

# Increment image count


count += 1

# Display the captured frame


cv2.imshow('Capture Images', frame)

# Break the loop when 'q' is pressed


if cv2.waitKey(1) & 0xFF == ord('q'):
break

# Release the camera and close OpenCV windows


cap.release()
cv2.destroyAllWindows()

# Main function to capture images


if __name__ == "__main__":
person_name = input("Enter the person's name: ")
image_count = int(input("Enter the number of images to capture: "))
capture_images(person_name, image_count)

You might also like