Skip to content

Commit e2ca754

Browse files
Merge pull request #42 from jonathanrocher/stage2_traited_script
Stage 2: add traited version of the script.
2 parents 573da8a + f1a1c53 commit e2ca754

1 file changed

Lines changed: 90 additions & 0 deletions

File tree

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
""" Script analyzing an image, detecting human faces inside it, and printing
2+
EXIF data about it.
3+
"""
4+
import PIL.Image
5+
from PIL.ExifTags import TAGS
6+
from skimage import data
7+
from skimage.feature import Cascade
8+
import matplotlib.pyplot as plt
9+
from matplotlib import patches
10+
from os.path import join
11+
import numpy as np
12+
13+
# ETS imports
14+
from traits.api import Dict, File, HasStrictTraits, List, observe
15+
16+
17+
class ImageFile(HasStrictTraits):
18+
""" Model to hold an image file.
19+
"""
20+
filepath = File
21+
22+
faces = List
23+
24+
metadata = Dict
25+
26+
def to_array(self):
27+
with PIL.Image.open(self.filepath) as img:
28+
return np.asarray(img)
29+
30+
@observe("filepath")
31+
def update_metadata(self, event):
32+
33+
with PIL.Image.open(self.filepath) as img:
34+
exif = img._getexif()
35+
self.metadata = {TAGS[k]: v for k, v in exif.items()
36+
if k in TAGS}
37+
38+
def detect_faces(self):
39+
# Load the trained file from the module root.
40+
trained_file = data.lbp_frontal_face_cascade_filename()
41+
42+
# Initialize the detector cascade.
43+
detector = Cascade(trained_file)
44+
45+
detected = detector.detect_multi_scale(img=self.to_array(),
46+
scale_factor=1.2,
47+
step_ratio=1,
48+
min_size=(60, 60),
49+
max_size=(600, 600))
50+
self.faces = detected
51+
52+
self.metadata["Number of faces detected"] = len(detected)
53+
54+
55+
# Select image file -----------------------------------------------------------
56+
57+
image_path = join("..", "sample_images", "IMG-0311_xmas_2020.JPG")
58+
image_path2 = join("..", "sample_images", "owls.jpg")
59+
60+
img = ImageFile()
61+
for path in [image_path, image_path2]:
62+
63+
img.filepath = path
64+
65+
# Detect faces ------------------------------------------------------------
66+
67+
img.detect_faces()
68+
69+
print(img.metadata)
70+
71+
# Visualize results -------------------------------------------------------
72+
73+
plt.imshow(img.to_array())
74+
img_desc = plt.gca()
75+
plt.set_cmap('gray')
76+
77+
for patch in img.faces:
78+
79+
img_desc.add_patch(
80+
patches.Rectangle(
81+
(patch['c'], patch['r']),
82+
patch['width'],
83+
patch['height'],
84+
fill=False,
85+
color='r',
86+
linewidth=2
87+
)
88+
)
89+
90+
plt.show()

0 commit comments

Comments
 (0)