RZHD
unknown
python
2 years ago
2.6 kB
6
Indexable
import cv2 # Load pre-trained model for detecting people person_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_fullbody.xml') # Load pre-trained model for detecting phones phone_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_mobilephone.xml') # Variables for tracking phone usage time phone_in_use = False phone_use_start = 0 phone_use_end = 0 # Video capturing object cap = cv2.VideoCapture('path_to_video_file.mp4') while True: # Read each frame from the video ret, frame = cap.read() if ret: # Convert frame to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect people in the frame people = person_cascade.detectMultiScale(gray, 1.1, 4) # Iterate over each detected person's bounding box for (x, y, w, h) in people: # Draw bounding box around the person cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) # Get ROI (Region of Interest) for phone detection within person's bounding box roi_gray = gray[y:y+h, x:x+w] # Detect phones within ROI phones = phone_cascade.detectMultiScale(roi_gray) # Check if any phones are detected within person's bounding box if len(phones) > 0: # Phone is in use if not phone_in_use: # Start tracking phone usage time phone_use_start = cv2.getTickCount() phone_in_use = True else: # Phone usage ended if phone_in_use: # Calculate phone usage time in seconds phone_use_end = cv2.getTickCount() phone_usage_time = (phone_use_end - phone_use_start) / cv2.getTickFrequency() # Check if phone usage time is greater than or equal to 3 seconds if phone_usage_time >= 3: # Person was using the phone for more than 3 seconds print("Phone usage detected for {:.2f} seconds".format(phone_usage_time)) phone_in_use = False # Display the resulting frame cv2.imshow('Video', frame) # Exit if 'q' is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break else: break # Release the capture and close windows cap.release() cv2.destroyAllWindows()
Editor is loading...