图片来自网上,如果侵权,告知则删除
>>>>>>>>批量修改文件名(常见文件操作,可以学习一下)
import os
path = './opencv/data/images'
# 获取该目录下所有文件,存入列表中
labelList = os.listdir(path)
n = 0
count = 1
for label in labelList:
print(label)
dirPath = os.path.join(path,label)
for img_name in os.listdir(dirPath):
old_img_path = os.path.join(dirPath,img_name)
# 设置新文件名
name = str(n+1)+'.' + str(label) + '.'+ str(count) +'.jpg'
# new_img_path = os.path.join(dirPath,name)
new_img_path = dirPath + '/' + name
print(old_img_path)
print(new_img_path)
os.rename(old_img_path, new_img_path)
count +=1
n+=1
>>>>>>>>进入正题
(一)读取图片
#导入cv模块
import cv2 as cv
#读取图片
img = cv.imread('face1.png')
#显示图片
cv.imshow('read_img',img)
#等待
cv.waitKey(0)
#释放内存
cv.destroyAllWindows()
(二)灰度转换
#导入cv模块
import cv2 as cv
#读取图片
img = cv.imread('face1.png')
#灰度转换
gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#显示灰度图片
cv.imshow('gray_img',gray_img)
#保存灰度图片
cv.imwrite('gray_face1.png',gray_img)
#显示图片
cv.imshow('read_img',img)
#等待
cv.waitKey(0)
#释放内存
cv.destroyAllWindows()
(三)修改尺寸
#导入cv模块
import cv2 as cv
#读取图片
img = cv.imread('face1.png')
#修改尺寸
resize_img = cv.resize(img,dsize=(200,200))
#显示原图
cv.imshow('img',img)
#显示修改后的
cv.imshow('resize_img',resize_img)
#打印原图尺寸大小
print('未修改',img.shape)
#打印修改后的大小
print('修改后',resize_img.shape)
#等待
while True:
if ord('q') == cv.waitKey(0):
break
cv.waitKey(0)
#灰度转换
gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#显示灰度图片
cv.imshow('gray_img',gray_img)
#保存灰度图片
cv.imwrite('gray_face1.png',gray_img)
#显示图片
cv.imshow('read_img',img)
#等待
cv.waitKey(0)
#释放内存
cv.destroyAllWindows()
(四)绘制矩形
#导入cv模块
import cv2 as cv
#读取图片
img = cv.imread('face1.png')
#坐标
x,y,w,h = 50,50,50,50
#绘制矩形
cv.rectangle(img,(x,y,x+w,y+h),color=(0,0,255),thickness=1)
#绘制圆形
cv.circle(img,center=(x+w,y+h),radius=50,color=(255,0,0),thickness=2)
#显示
cv.imshow('re_img',img)
#等待
while True:
if ord('q') == cv.waitKey(0):
break
#释放内存
cv.destroyAllWindows()
(五)人脸检测
#导入cv模块
import cv2 as cv
def face_detect_demo(img):
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 分类器
face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
face = face_detect.detectMultiScale(gray,1.01,5,0,(100,100),(300,300))
for x,y,w,h in face:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
cv.imshow('res',img)
# 读取图片
img = cv.imread('face1.png')
# 检测函数
face_detect_demo(img)
# 等待
while True:
if ord('q') == cv.waitKey(0):
break
# 释放内存
cv.destroyAllWindows()
(六)检测多个人脸
#导入cv模块
import cv2 as cv
def face_detect_demo(img):
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 分类器
# face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
# face = face_detect.detectMultiScale(gray,1.1,5,0,(10,10),(100,100))
face = face_detect.detectMultiScale(gray,1.1)
for x,y,w,h in face:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
cv.imshow('res',img)
# 读取图片
img = cv.imread('multi_face1.png')
# 检测函数
face_detect_demo(img)
# 等待
while True:
if ord('q') == cv.waitKey(0):
break
# 释放内存
cv.destroyAllWindows()
(七)视频检测
#导入cv模块
import cv2 as cv
def face_detect_demo(img):
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 分类器
# face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
# face = face_detect.detectMultiScale(gray,1.1,5,0,(10,10),(100,100))
face = face_detect.detectMultiScale(gray,1.1)
for x,y,w,h in face:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
cv.imshow('res',img)
# 读取摄像头
cap = cv.VideoCapture(0)
# cap = cv.VideoCapture("face.mp4")
# 循环
while True:
flag,frame = cap.read()
if not flag:
break
face_detect_demo(frame)
if ord('q') == cv.waitKey(0):
break
# 释放内存
cv.destroyAllWindows()
# 释放摄像头
cap.release()
(八)拍照保存
# 导入模块
import cv2
import os
# 摄像头
cap = cv2.VideoCapture(0)
num = 1
while(cap.isOpened()):#检测是否在开启状态
flag,frame = cap.read() # 得到每帧图像
cv2.imshow("Capture_Test",frame) #显示图像
k = cv2.waitKey(1) & 0xFF #按键判断
if k == ord('s'):#保存
path = os.path.join('E:/faceRecognition/save_img/',str(num)+"_name"+".jpg")
print(path)
cv2.imwrite(path,frame)
print("success to save"+str(num)+".jpg")
print("----------------")
num+=1
elif k == ord(' '):
break
# 释放摄像头
cap.release()
# 释放内存
cv2.destroyAllWindows()
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>准备数据集>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
训练集train
注意:第一个.前面是id,后面是label
测试集test
(九)数据训练
import os
import cv2
from PIL import Image
import numpy as np
def getImageAndLabels(path):
#存储人脸数据
facesSamples = []
# 储存姓名数据
ids = []
#储存图片信息
# imagePaths = [(os.path.join(path,f) for f in os.listdir(path))]
imagePaths = []
for f in os.listdir(path):
img_path = path+'/' + f
imagePaths.append(img_path)
#加载分类器
face_detect = cv2.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
# print(imagePaths)
#遍历列表中的图片
for imagePath in imagePaths:
# print(imagePath)
#打开图片,灰度化PIL有九种不同模式
PIL_img = Image.open(imagePath).convert('L')
#将图像转换为数组,以黑白深浅
img_numpy = np.array(PIL_img,'uint8')
#保存图片人脸检测
faces = face_detect.detectMultiScale(img_numpy)
#获取每张图片的id和姓名
id = int(os.path.split(imagePath)[1].split('.')[0])
#预测无面容的图片
for x,y,w,h in faces:
ids.append(id)
facesSamples.append(img_numpy[y:y+h,x:x+w])
#打开脸部特征和id
# print('id:',id)
# print('fs:',facesSamples)
return facesSamples,ids
if __name__ == '__main__':
# 图片路径
path = './opencv/data/images'
# 获取该目录下所有文件,存入列表中
labelList = os.listdir(path)
facesList = []
idsList = []
for label in labelList:
dirPath = path + '/' + str(label)
# print('dirPath',dirPath)
# 获取图像数组和id标签数组和姓名
faces,ids = getImageAndLabels(dirPath)
# print(faces)
# print(ids)
for face in faces:
facesList.append(face)
for id in ids:
idsList.append(id)
# # 加载识别器
# recognizer = cv2.face.LBPHFaceRecognizer_create()
# #训练
# recognizer.train(faces,np.array(ids))
# #保存文件
# recognizer.write("trainer/trainer.yml")
# print(facesList)
# print(idsList)
# 加载识别器
recognizer = cv2.face.LBPHFaceRecognizer_create()
#训练
recognizer.train(facesList,np.array(idsList))
#保存文件
recognizer.write("trainer/trainer.yml")
(十)人脸识别
import cv2
import numpy as np
import os
# coding=utf-8
import urllib
import urllib.request
import hashlib
#加载训练数据集文件
recogizer=cv2.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/trainer.yml')
names=[]
#准备识别的图片
def face_detect_demo(img):
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#转换为灰度
face_detector = cv2.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
# face=face_detector.detectMultiScale(gray,1.1,5,cv2.CASCADE_SCALE_IMAGE,(100,100),(300,300))
face=face_detector.detectMultiScale(gray,1.1)
for x,y,w,h in face:
cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
cv2.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)
# 人脸识别
ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
print('标签id:',ids,'置信评分:', confidence)
if confidence > 80:
cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 255, 0), 1)
# cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
else:
# cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
cv2.namedWindow("result", cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
cv2.resizeWindow("result", 400, 400)
cv2.moveWindow("result", 500, 250) # 显示框位置,左上角为原点(0, 0)坐标,第一个是x坐标,第二个是y坐标
cv2.imshow('result',img)
#print('bug:',ids)
cv2.waitKey(0)
cv2.destroyAllWindows()
def name():
# path = './data/jm/'
path = './opencv/data/images'
names = []
# 获取该目录下所有文件,存入列表中
labelList = os.listdir(path)
for label in labelList:
names.append(label)
print(names)
return names
names = name()
path = './test'
for img_name in os.listdir(path):
img_path = path + '/' + img_name
img = cv2.imread(img_path)
face_detect_demo(img)
# cap=cv2.VideoCapture('1.mp4')
# while True:
# flag,frame=cap.read()
# if not flag:
# break
# face_detect_demo(frame)
# if ord(' ') == cv2.waitKey(10):
# break
# cap.release()
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>实验效果>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
文章来源:https://www.toymoban.com/news/detail-759823.html
本实验数据很少,做了个小demo,喜欢的话点个赞👍+收藏!!!!!!!!!!!! 文章来源地址https://www.toymoban.com/news/detail-759823.html
到了这里,关于OpenCV人脸识别项目(训练+测试)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!