基础知识(七)opencv、python、人脸框检测

一、环境搭建

电脑系统:window7 64位

opencv版本:opencv 2.49

python版本:python 2.7

1、首先就是安装opencv,从官网下载.exe文件,然后直接安装。安装完opencv后,找到文件:cv2.pyd。这个文件,我安装完后,是放在:opencv\build\python\2.7\x64。因为我的电脑是64位所以选择x64下的文件cv2.pyd。

2、把cv2.pyd文件放到python安装目录里的:Lib\site-packages文件夹下。这样就OK了,接着就可以直接调用opencv库了。

二、人脸检测

import numpy as np
import cv2
import cv2.cv as cv
from matplotlib import pyplot as plt

face_cascade = cv2.CascadeClassifier('C:\Program Files\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')


img = cv2.imread('113.jpg')
gray = cv2.cvtColor(img,cv2.cv.CV_BGR2GRAY)

divisor=8
h, w =np.shape(img)[:2]
minSize=(w/divisor, h/divisor)
color = (0,0,0)
faces = face_cascade.detectMultiScale(gray, 1.2, 2, cv2.CASCADE_SCALE_IMAGE,minSize)


if len(faces)>0:
    for faceRect in faces:  
        x, y, w, h = faceRect
        cv2.rectangle(img, (x, y), (x+w, y+h), color)
        roi = img[y:(h+y), x:(w+x)]

cv2.imshow('img',img)
cv2.imshow('facerect',roi)
cv2.waitKey(0)
cv2.destroyAllWindows()
上面的cv2.CascadeClassifier函数的参数是.xml所在的路径。结果如下:
基础知识(七)opencv、python、人脸框检测_第1张图片


import numpy as np  
import cv2  
import cv2.cv as cv  
from matplotlib import pyplot as plt  


def GetFileList(FindPath,FlagStr=[]):      
	import os
	FileList=[]
	FileNames=os.listdir(FindPath)
	if len(FileNames)>0:
		for fn in FileNames:
			if len(FlagStr)>0:
				if IsSubString(FlagStr,fn):
					fullfilename=os.path.join(FindPath,fn)
					FileList.append(fullfilename)
			else:
				fullfilename=os.path.join(FindPath,fn)
				FileList.append(fullfilename)

   
	if len(FileList)>0:
		FileList.sort()

	return FileList
def IsSubString(SubStrList,Str):      
	flag=True
	for substr in SubStrList:
		if not(substr in Str):
			flag=False

	return flag



def facedetect(newname,filepath,face_cascade):
	
	img = cv2.imread(filepath)  
	print filepath
	gray = cv2.cvtColor(img,cv2.cv.CV_BGR2GRAY)  
      
	divisor=8  
	height, weight =np.shape(img)[:2]  
	minSize=(weight/divisor, height/divisor)  
	color = (0,0,0)  
	faces = face_cascade.detectMultiScale(gray, 1.2, 2, cv2.CASCADE_SCALE_IMAGE,minSize)  
	print faces
      
	if len(faces)>0:  
		for faceRect in faces:    
			x, y, w, h = faceRect  
			img0=np.zeros((h+0.2*h,w+0.2*w,3))
			m,n,c=img0.shape
			miny=max(0,y-0.3*h)
			minx=max(0,(x-0.3*w))
			maxy=min(height,(y+1.3*h))
			maxx=min(weight,(x+1.3*w))
			roi=img[miny:maxy,minx:maxx]
			rectshape=roi.shape
			maxlenght=max(rectshape[0],rectshape[1])
			img0=np.zeros((maxlenght,maxlenght,3))	
			img0[(maxlenght*.5-rectshape[0]*.5):(maxlenght*.5+rectshape[0]*.5),(maxlenght*.5-rectshape[1]*.5):(maxlenght*.5+rectshape[1]*.5)]=roi
			cv2.imwrite(newname,img0)


face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')  
imgfile=GetFileList('face','.jpg')
i=0
for imgf in imgfile:
	name='face1/'+str(i)+'.jpg'
	i+=1
	facedetect(name,imgf,face_cascade)

人脸裁剪为矩阵,并填充

import numpy as np  
import cv2  
import cv2.cv as cv  
from matplotlib import pyplot as plt  


def GetFileList(FindPath,FlagStr=[]):      
	import os
	FileList=[]
	FileNames=os.listdir(FindPath)
	if len(FileNames)>0:
		for fn in FileNames:
			if len(FlagStr)>0:
				if IsSubString(FlagStr,fn):
					fullfilename=os.path.join(FindPath,fn)
					FileList.append(fullfilename)
			else:
				fullfilename=os.path.join(FindPath,fn)
				FileList.append(fullfilename)

   
	if len(FileList)>0:
		FileList.sort()

	return FileList
def IsSubString(SubStrList,Str):      
	flag=True
	for substr in SubStrList:
		if not(substr in Str):
			flag=False

	return flag



def facedetect(newname,filepath,face_cascade):
	
	img = cv2.imread(filepath)  
	gray = cv2.cvtColor(img,cv2.cv.CV_BGR2GRAY)  
      
	divisor=8  
	height, weight =np.shape(img)[:2]  
	minSize=(weight/divisor, height/divisor)  
	color = (0,0,0)  
	faces = face_cascade.detectMultiScale(gray, 1.2, 2, cv2.CASCADE_SCALE_IMAGE,minSize)  
	print faces
      
	if len(faces)>0:  
		for faceRect in faces:    
			x, y, w, h = faceRect  
			img0=np.zeros((h+0.2*h,w+0.2*w,3))
			m,n,c=img0.shape
			miny=max(0,y-0.3*h)
			minx=max(0,(x-0.3*w))
			maxy=min(height,(y+1.3*h))
			maxx=min(weight,(x+1.3*w))
			roi=img[miny:maxy,minx:maxx]
			rectshape=roi.shape
			maxlenght=max(rectshape[0],rectshape[1])
			img0=np.zeros((maxlenght,maxlenght,3))	
			img0[(maxlenght*.5-rectshape[0]*.5):(maxlenght*.5+rectshape[0]*.5),(maxlenght*.5-rectshape[1]*.5):(maxlenght*.5+rectshape[1]*.5)]=roi
			cv2.imwrite(newname,img0)


face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')  
imgfile=GetFileList('ff')
i=0
for imgf in imgfile:
	name='ff_face/'+str(i)+'.jpg'
	i+=1
	facedetect(name,imgf,face_cascade)





**********************作者:hjimce   时间:2015.9.1  联系QQ:1393852684   地址:http://blog.csdn.net/hjimce 转载请保留本行信息********************



你可能感兴趣的:(基础知识)