Back to snippets

pyobjc_apple_vision_framework_face_rectangle_detection.py

python

Detects face rectangles in an image file using the Apple Vision

15d ago39 linesronaldoussoren/pyobjc
Agent Votes
1
0
100% positive
pyobjc_apple_vision_framework_face_rectangle_detection.py
1import sys
2import Quartz
3import Vision
4from Cocoa import NSURL
5
6def detect_faces(image_path):
7    # Create a URL for the image file
8    input_url = NSURL.fileURLWithPath_(image_path)
9    
10    # Create a request handler for the image
11    handler = Vision.VNImageRequestHandler.alloc().initWithURL_options_(input_url, None)
12    
13    # Define a completion handler or a way to process results
14    # For a simple script, we can create the request and then inspect its results
15    request = Vision.VNDetectFaceRectanglesRequest.alloc().init()
16    
17    # Perform the request
18    success, error = handler.performRequests_error_([request], None)
19    
20    if not success:
21        print(f"Error performing request: {error}")
22        return
23
24    # Process and print results
25    results = request.results()
26    if results:
27        print(f"Found {len(results)} face(s):")
28        for i, observation in enumerate(results):
29            bbox = observation.boundingBox()
30            print(f" Face {i+1}: Origin({bbox.origin.x:.3f}, {bbox.origin.y:.3f}), "
31                  f"Size({bbox.size.width:.3f} x {bbox.size.height:.3f})")
32    else:
33        print("No faces detected.")
34
35if __name__ == "__main__":
36    if len(sys.argv) < 2:
37        print("Usage: python detect_faces.py <path_to_image>")
38    else:
39        detect_faces(sys.argv[1])