How to put OpenCV in Raspberry Pi and easily collect images of face detection results with Python

Introduction

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.

OpenCV installation

Install with the following command. By the way, it is for Python 2.7.

python


$ sudo apt install libopencv-dev python-opencv

function

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.

Loading the library

Load the library you want to use.

python


import cv2
import sys
from PIL import Image
import urllib
import os

Creating a folder for images

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")

Download image data

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())

Image data processing

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)

Face detection process

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 and save the face image from the detection result

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 (^-^)

in conclusion

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

How to put OpenCV in Raspberry Pi and easily collect images of face detection results with Python
How to collect images in Python
How to collect face images relatively easily
Hello World and face detection with OpenCV 4.3 + Python
I got an error when I put opencv in python3 with Raspberry Pi [Remedy]
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Face detection from images taken with Raspberry Pi camera
Wall to put OpenCV 3.1.0 in raspberry pi 3 and run sample on python3: ImportError: No module named cv2 solution
Face detection with Python + OpenCV
Send experiment results (text and images) to slack with Python
Comparison of how to use higher-order functions in Python 2 and 3
How to log in to AtCoder with Python and submit automatically
How to process camera images with Teams and Zoom Volume of processing in animation style
[Python] Collect images easily with icrawler!
How to install OpenCV on Cloud9 and run it in Python
How to make a surveillance camera (Security Camera) with Opencv and Python
How to use python put in pyenv on macOS with PyCall
Draw a watercolor illusion with edge detection in Python3 and openCV3
I tried to automatically collect images of Kanna Hashimoto with Python! !!
[Python] Try to recognize characters from images with OpenCV and pyocr
Face detection with Python + OpenCV (rotation invariant)
[Itertools.permutations] How to put permutations in Python
Capturing images with Pupil, python and OpenCV
How to work with BigQuery in Python
How to check opencv version in python
[python, openCV] base64 Face recognition with images
How to use is and == in Python
How to draw OpenCV images in Pygame
How to crop the lower right part of the image with Python OpenCV
How to get the date and time difference in seconds with python
[Python] How to put any number of standard inputs in a list
How to put a half-width space before letters and numbers in Python.
RabbitMQ message notification app in Python with Growl ~ with Raspberry Pi and Julius ~
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
How to generate a QR code and barcode in Python and read it normally or in real time with OpenCV
[REAPER] How to play with Reascript in Python
How to generate permutations in Python and C ++
Convert PDFs to images in bulk with Python
Summary of how to import files in Python 3
How to use Raspberry Pi pie camera Python
How to crop an image with Python + OpenCV
Summary of how to use MNIST in Python
How to specify attributes with Mock of python
Get CPU information of Raspberry Pi with Python
How to use tkinter with python in pyenv
(Diary 1) How to create, reference, and register data in the SQL database of Microsoft Azure service with python
Wavelet transform of images with PyWavelets and OpenCV
Try to detect an object with Raspberry Pi ~ Part 1: Comparison of detection speed ~
[Python] How to handle Japanese characters with openCV
Connect to MySQL with Python on Raspberry Pi
How to plot autocorrelation and partial autocorrelation in python
How to get a list of files in the same directory with python
Measure CPU temperature of Raspberry Pi with Python
How to achieve access by attribute and retention of insertion order in Python dict
[Super easy] Simultaneous face recognition and facial expression recognition in real time with Python and OpenCV!
How to store Python function in Value of dictionary (dict) and call function according to Key
I made a program to convert images into ASCII art with Python and OpenCV
How to identify the element with the smallest number of characters in a Python list?
Extract images and tables from pdf with python to reduce the burden of reporting
[Note] How to write QR code and description in the same image with python
How to count the number of occurrences of each element in the list in Python with weight