It was quite difficult to collect images of human faces necessary for machine learning, so I made a script to reduce the workload a little.
Install with the following command. By the way, it is for Python 2.7.
python
$ sudo apt install libopencv-dev python-opencv
If you specify the image URL of the group photo, the image is downloaded from the Internet, face detection is performed, and the image of the detection result is saved.
Load the library you want to use.
python
import cv2
import sys
from PIL import Image
import urllib
import os
Create folders to save the images for detection and results.
python
if os.path.exists("input") == False:
os.mkdir("input")
if os.path.exists("output") == False:
os.mkdir("output")
Saves the image from the specified URL to the input folder. It also gets the name of the image file from the URL.
python
url = "http://hoge.com/photo.jpg "
#Get file name
tmp = url.split("/")
imgname = tmp[len(tmp)-1]
imgpath = "input/" + imgname
#Download image data
response = urllib.urlopen(url)
with open(imgpath, "wb") as fout:
fout.write(response.read())
If it is full color, it takes time to process, so convert it to grayscale.
python
#Image data reading
image = cv2.imread(imgpath)
#Grayscale conversion
image_gray = cv2.cvtColor(image, cv2.cv.CV_BGR2GRAY)
Reads and detects trained data for face detection.
python
#HAAR classifier designation
cascade_path = "haarcascades/haarcascade_frontalface_alt.xml"
#Acquire the features of the cascade classifier
cascade = cv2.CascadeClassifier(cascade_path)
#Detection process
faces = cascade.detectMultiScale(image_gray, scaleFactor=1.1, minNeighbors=1, minSize=(1, 1))
print "Detection result",len(faces),"Man"
Cut the face image from the image data before converting to grayscale and save it. At this time, resize the image size to 50x50 so that it is easy to use for machine learning.
python
img = Image.open(imgpath)
for i in range(len(faces)):
[x,y,w,h] = faces[i]
imgCroped = img.crop((x,y,x+w,y+h)).resize((50, 50))
filename = "output/%s_%02d.jpg " % (imgname.split(".")[0], i)
imgCroped.save(filename)
did it! !! Some things other than faces are detected, but generally satisfied (^-^)
If you ask Google Sensei for a "group photo", you will see a large number of high-resolution photos. I was surprised a little.
Recommended Posts