|
| 1 | +""" Script analyzing an image, detecting human faces inside it, and printing |
| 2 | +EXIF data about it. |
| 3 | +""" |
| 4 | +from os.path import join |
| 5 | + |
| 6 | +import PIL.Image |
| 7 | +from PIL.ExifTags import TAGS |
| 8 | +from skimage import data |
| 9 | +from skimage.feature import Cascade |
| 10 | +import matplotlib.pyplot as plt |
| 11 | +import numpy as np |
| 12 | +from matplotlib import patches |
| 13 | + |
| 14 | +# Select image file ----------------------------------------------------------- |
| 15 | + |
| 16 | +image_paths = [ |
| 17 | + join("..", "sample_images", "IMG-0311_xmas_2020.JPG"), |
| 18 | + join("..", "sample_images", "owls.jpg") |
| 19 | +] |
| 20 | + |
| 21 | +# Load the trained file from the module root. |
| 22 | +trained_file = data.lbp_frontal_face_cascade_filename() |
| 23 | + |
| 24 | +# Initialize the detector cascade. |
| 25 | +detector = Cascade(trained_file) |
| 26 | + |
| 27 | +for path in image_paths: |
| 28 | + img = PIL.Image.open(path) |
| 29 | + |
| 30 | + img_metadata = {TAGS[k]: v for k, v in img._getexif().items() if k in TAGS} |
| 31 | + |
| 32 | + # Detect faces ------------------------------------------------------------ |
| 33 | + |
| 34 | + detected = detector.detect_multi_scale(img=np.asarray(img), |
| 35 | + scale_factor=1.2, |
| 36 | + step_ratio=1, |
| 37 | + min_size=(60, 60), |
| 38 | + max_size=(600, 600)) |
| 39 | + |
| 40 | + img_metadata["Number of faces detected"] = len(detected) |
| 41 | + print(img_metadata) |
| 42 | + |
| 43 | + # Visualize results ------------------------------------------------------- |
| 44 | + |
| 45 | + plt.imshow(img) |
| 46 | + img_desc = plt.gca() |
| 47 | + |
| 48 | + for patch in detected: |
| 49 | + |
| 50 | + img_desc.add_patch( |
| 51 | + patches.Rectangle( |
| 52 | + (patch['c'], patch['r']), |
| 53 | + patch['width'], |
| 54 | + patch['height'], |
| 55 | + fill=False, |
| 56 | + color='r', |
| 57 | + linewidth=2 |
| 58 | + ) |
| 59 | + ) |
| 60 | + |
| 61 | + plt.show() |
0 commit comments