以前在做图像识别处理算法实验的时候,基本都是使用别人处理好的数据集,今天想自己处理一些图像数据,于是自己写了一个小脚本程序(有一些冗余代码),主程序如下所示,其中需要opencv的一个人脸识别文件
haarcascade_frontalface_default.xml
需要用到的同学请自行寻找opencv源码中该文件
其中主要参考文章如下:
以下是我的代码:
#!/usr/bin/python
#coding=utf-8
''' face detect
https://github.com/seathiefwang/FaceRecognition-tensorflow
http://tumumu.cn/2017/05/02/deep-learning-face/
'''
# pylint: disable=invalid-name
import os
import random
import numpy as np
import cv2
import time
def createdir(*args):
''' create dir'''
for item in args:
if not os.path.exists(item):
os.makedirs(item)
IMGSIZE = 64
def getpaddingSize(shape):
''' get size to make image to be a square rect '''
h, w = shape
longest = max(h, w)
result = (np.array([longest]*4, int) - np.array([h, h, w, w], int)) // 2
return result.tolist()
def dealwithimage(img, h=64, w=64):
''' dealwithimage '''
#img = cv2.imread(imgpath)
top, bottom, left, right = getpaddingSize(img.shape[0:2])
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0, 0])
img = cv2.resize(img, (h, w))
return img
def relight(imgsrc, alpha=1, bias=0):
'''relight'''
imgsrc = imgsrc.astype(float)
imgsrc = imgsrc * alpha + bias
imgsrc[imgsrc < 0] = 0
imgsrc[imgsrc > 255] = 255
imgsrc = imgsrc.astype(np.uint8)
return imgsrc
def getfacefromcamera(indir,outdir):
createdir(outdir)
#camera = cv2.VideoCapture(0)
haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
n = 1
while 1:
if (n <= 5):
print('It`s processing %s image.' % n)
# 读帧
#success, img = camera.read()
for file in os.listdir(indir):
singlefilename=indir+"/"+file
if(singlefilename.endswith('.png')):
img =cv2.imread(singlefilename)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = haar.detectMultiScale(gray_img, 1.3, 5)
for f_x, f_y, f_w, f_h in faces:
face = img[f_y:f_y+f_h, f_x:f_x+f_w]
face = cv2.resize(face, (IMGSIZE, IMGSIZE))
cv2.imwrite(os.path.join(outdir, str(n)+'.png'), face)
img = cv2.rectangle(img, (f_x, f_y), (f_x + f_w, f_y + f_h), (255, 0, 0), 2)
n+=1
cv2.imshow('img', img)
time.sleep(2)
key = cv2.waitKey(30) & 0xff
if key == 27:
break
else:
break
if __name__ == '__main__':
#name = input('please input yourename: ')
getfacefromcamera('C:/Users/AUGUSTRUSH/Desktop/tangwei','C:/Users/AUGUSTRUSH/Desktop/tangwei/new1')
处理完效果如下图所示:
TIM截图20180328160036.png
网友评论