Cut out face with Python + OpenCV

Target

I want to implement face recognition in TensorFlow. I want to crop a face from an image to collect and normalize face data

Serious memorandum

environment

jupyter notebook OpenCV3.0 Python3.5

Put Lena and haarcascade_frontalface_alt.xml in the same directory as the .py file, or rewrite the path.

code

trimming.py


import cv2
import matplotlib.pyplot as plt
%matplotlib inline

#Image loading
src_image = cv2.imread('lenna.jpeg')
#Convert to grayscale
dst_image = cv2.cvtColor(src_image,cv2.COLOR_RGB2GRAY)
#Haar-like classifier read
cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
#Store the coordinate information of the face detected by cascading in facerect
#[Top left X coordinate of the rectangle,Upper left Y coordinate of the rectangle,The length of the face image in the X-axis direction,The length of the face image in the Y-axis direction]I'm worried if it's here
facerect = cascade.detectMultiScale(dst_image, scaleFactor=1.1, minNeighbors=1, minSize=(1, 1))
#When one or more faces are detected
if len(facerect) > 0:
    for rect in facerect:
        dst_image = dst_image[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]
#When no face is detected
else:
    print("no face")
#When this is done, it becomes grayscale. Mystery
dst_image = cv2.cvtColor(dst_image,cv2.COLOR_GRAY2RGB)

plt.imshow(dst_image)

Summary

When displaying a color image read by imread () in grayscale with imshow (), It seems that you have to change from RGB to gray with cvtColor and then from gray to RGB with cvtColor again. Perhaps

I will add this area as soon as I understand it.

2016/11/30 postscript

You can't save this, right? That's why I made a mechanism to trim and save. Say goodbye to jupyter I'm working on PyCharm. pycharm convenient

trimming.py


import cv2

cascade_path = "./haarcascades/haarcascade_frontalface_alt.xml"
origin_image_path = "Image folder path"
dir_path = "Image save destination path"

i = 0

for line in open('Text file path','r'):
    line = line.rstrip()
    print(line)
    image = cv2.imread(origin_image_path+line,0)
    if image is None:
        print('Not open : ',line)
        quit()

    cascade = cv2.CascadeClassifier(cascade_path)
    facerect = cascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=1, minSize=(10, 10))

    if len(facerect) > 0:
        for rect in facerect:
            #Cut out only the face and save
            x = rect[0]
            y = rect[1]
            width = rect[2]
            height = rect[3]
            dst = image[y:y + height, x:x + width]
            save_path = dir_path + '/' + 'image(' + str(i) + ')' + '.jpg'
            #Saving recognition results
            cv2.imwrite(save_path, dst)
            print("save!")
            i += 1
print("Finish")

You can write line by line to the text by doing $ ls> hoge.txt in the folder containing the image. While reading the name of the written image, open it, trim it, and save it.

rstrip () The image cannot be read for some reason unless it is bitten. .. ..

But isn't this something like resizing the image? (Continue)

Reference site

Cut out a part of the statue and save http://clngn.hatenablog.com/entry/20120113/1326442326 Play with Python -part1- (Face recognition with OpenCV) http://www.takunoko.com/blog/python%E3%81%A7%E9%81%8A%E3%82%93%E3%81%A7%E3%81%BF%E3%82%8B-part1-opencv%E3%81%A7%E9%A1%94%E8%AA%8D%E8%AD%98/

Recommended Posts

Cut out face with Python + OpenCV
Face detection with Python + OpenCV
Cut out an image with python
Try face recognition with python + OpenCV
Face recognition with camera with opencv3 + python2.7
Cut out frames from video by 1 second with Python + OpenCV
Face detection with Python + OpenCV (rotation invariant)
[python, openCV] base64 Face recognition with images
Binarization with OpenCV / Python
Hello World and face detection with OpenCV 4.3 + Python
Performance comparison of face detector with Python + OpenCV
Face detection from multiple image files with openCV, cut out and save
Face recognition with Python's OpenCV
[Python] Using OpenCV with Python (Basic)
Face detection with Python + dlib
Face recognition / cutting with OpenCV
Try face recognition with Python
Using OpenCV with Python @Mac
Anime face detection with OpenCV
Shining life with Python and OpenCV
Face detection with YOLO Face (Windows10, Python3.6)
[Python] Using OpenCV with Python (Image Filtering)
Neural network with OpenCV 3 and Python 3
[Python] Using OpenCV with Python (Image transformation)
Face detection with Lambda (Python) + Rekognition
[Python] Using OpenCV with Python (Edge Detection)
A memo when face is detected with Python + OpenCV quickly
Easy Python + OpenCV programming with Canopy
[OpenCV] Personal identification with face photo
Load gif images with Python + OpenCV
Find image similarity with Python + OpenCV
Use OpenCV with Python 3 in Window
Draw an illustration with Python + OpenCV
Track baseball balls with Python + OpenCV
Graph Based Segmentation with Python + OpenCV
I tried face recognition with OpenCV
Draw arrows (vectors) with opencv / python
Basic study of OpenCV with Python
[Python] Face detection by OpenCV (Haar Cascade)
Save video frame by frame with Python OpenCV
Capturing images with Pupil, python and OpenCV
I tried non-photorealistic rendering with Python + opencv
Image processing with Python & OpenCV [Tone Curve]
Image acquisition from camera with Python + OpenCV
Create miscellaneous Photoshop videos with Python + OpenCV ③ Create miscellaneous Photoshop videos
[Python] Read images with OpenCV (for beginners)
Serverless face recognition API made with Python
Cut out and connect images with ImageMagick
Until you can use opencv with python
Light image processing with Python x OpenCV
Smoothing edge-saved with python + OpenCV (BilateralFilter, NLMeansFilter)
FizzBuzz with Python3
Scraping with Python
Statistics with python
Python2.7 + CentOS7 + OpenCV3
Scraping with Python
Python with Go
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python