基础知识(七)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库了。

二、人脸检测

<span style="font-size:18px;">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()</span>
上面的cv2.CascadeClassifier函数的参数是.xml所在的路径。结果如下:



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 转载请保留本行信息********************



  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值