刚开的一个小板块——AI智能,算是一个学习AI的过程记录吧,小白白白…白的不能再白了,人家叫人工智能,我这人工智障….
在网上看到个小项目,用Python写的一个人脸识别系统,基于OpenCV实现的,现在来学习下….完整项目联系本人QQ要,或者留言邮箱即可….
环境
数据库选一个就行了,模块缺啥就在上面安装什么即可
Python版本我用的3.7
下面这些模块是我暂时用到的,其他的遇到报错就直接添加安装即可
1.使用pycharm的在解释器插件搜索模块安装就行了,可视化操作
2.或者使用命令安装 pip install 模块名 (需要注意的地方是pip的版本要高,低版本可能安装不上)
加速使用国内镜像源 -i https://pypi.tuna.tsinghua.edu.cn/simple
import datetime import os import shutil import time import cv2 import sys import numpy as np import pymysql import pyttsx3 from PIL import Image
1.读取图片
#导入模块 import cv2 as cv #读取图片 img=cv.imread('lena.jpg') #路径中不能有中文,否则加载图片失败 #显示图片 cv.imshow('read_img',img) #等待键盘输入 单位毫秒 传入0 则就是无限等待 cv.waitKey(3000) #释放内存 由于OpenCV底层是C++编写的 cv.destroyAllWindows()
2.将图片灰度转换
import cv2 as cv img=cv.imread('lena.jpg') cv.imshow('BGR_img',img) #将图片灰度转换 gray_img=cv.cvtColor(img,cv.COLOR_BGR2GRAY) cv.imshow('gray_img',gray_img) #保存图片 cv.imwrite('gray_lena.jpg',gray_img) cv.waitKey(0) cv.destroyAllWindows()
3.修改图片的尺寸
import cv2 as cv img=cv.imread('lena.jpg') cv.imshow('img',img) print('原来图片的形状',img.shape) # resize_img=cv.resize(img,dsize=(200,240)) resize_img=cv.resize(img,dsize=(600,560)) print('修改后图片的形状:',resize_img.shape) cv.imshow('resize_img',resize_img) # cv.waitKey(0) #只有输入q时候,退出 while True: if ord('q')==cv.waitKey(0): break cv.destroyAllWindows()
4.绘制矩形
import cv2 as cv img=cv.imread('lena.jpg') #左上角的坐标是(x,y) 矩形的宽度和高度(w,h) x,y,w,h=100,100,100,100 cv.rectangle(img,(x,y,x+w,y+h),color=(0,255,255),thickness=3) #BGR #绘制圆center元组指圆点的坐标 radius:半径 x,y,r=200,200,100 cv.circle(img,center=(x,y),radius=r,color=(0,0,255),thickness=2) #显示图片 cv.imshow('rectangle_img',img) cv.waitKey(0) cv.destroyAllWindows()
5.人脸检测
import cv2 as cv def face_detect_demo(): #将图片转换为灰度图片 gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) #加载特征数据 face_detector=cv.CascadeClassifier('./haarcascade_frontalface_default.xml') #haarcascade_frontalface_default.xml OpenCV下载之后data/haarcascades目录下 faces=face_detector.detectMultiScale(gray) for x,y,w,h in faces: cv.rectangle(img,(x,y),(x+w,y+h),color=(0,255,0),thickness=2) cv.imshow('result',img) #加载图片 img=cv.imread('lena.jpg') face_detect_demo() cv.waitKey(0) cv.destroyAllWindows()
6.检测多张人脸
import cv2 as cv def face_detect_demo(): #将图片灰度 gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) #加载特征数据 face_detector = cv.CascadeClassifier('./haarcascade_frontalface_default.xml') faces = face_detector.detectMultiScale(gray) for x,y,w,h in faces: print(x,y,w,h) cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2) cv.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=2) #显示图片 cv.imshow('result',img) #加载图片 img=cv.imread('face3.jpg') #调用人脸检测方法 face_detect_demo() cv.waitKey(0) cv.destroyAllWindows()
7.检测视频中的人脸
import cv2 as cv def face_detect_demo(img): #将图片灰度 gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) #加载特征数据 face_detector = cv.CascadeClassifier('./haarcascade_frontalface_default.xml') faces = face_detector.detectMultiScale(gray) for x,y,w,h in faces: cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2) cv.circle(img,center=(x+w//2,y+h//2),radius=(w//2),color=(0,255,0),thickness=2) cv.imshow('result',img) #读取视频 #cap=cv.VideoCapture('video.mp4') cap=cv.VideoCapture(0) while True: flag,frame=cap.read() print('flag:',flag,'frame.shape:',frame.shape) if not flag: break face_detect_demo(frame) if ord('q') == cv.waitKey(10): break cv.destroyAllWindows() cap.release()
8.训练数据
import os import cv2 import sys 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)] #检测人脸 face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') #遍历列表中的图片 for imagePath in imagePaths: #打开图片 PIL_img=Image.open(imagePath).convert('L') #将图像转换为数组 img_numpy=np.array(PIL_img,'uint8') faces = face_detector.detectMultiScale(img_numpy) #获取每张图片的id id=int(os.path.split(imagePath)[1].split('.')[0]) for x,y,w,h in faces: facesSamples.append(img_numpy[y:y+h,x:x+w]) ids.append(id) return facesSamples,ids if __name__ == '__main__': #图片路径 path='./data/jm/' #获取图像数组和id标签数组 faces,ids=getImageAndLabels(path) #获取训练对象 recognizer=cv2.face.LBPHFaceRecognizer_create() recognizer.train(faces,np.array(ids)) #保存文件 recognizer.write('trainer/trainer.yml')
9.人脸识别
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') # recogizer.read('trainer/trainer.yml') names = [] warningtime = 0 # 准备识别的图片 def face_detect_demo(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度 # face_detector = cv2.CascadeClassifier( # '/Users/huangjw/Downloads/opencv-4.x/data/haarcascades/haarcascade_frontalface_alt2.xml') # 加载分类器(opencv已经训练好了) face_detector = cv2.CascadeClassifier( './haarcascade_frontalface_default.xml') face = face_detector.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (500, 500)) # face=face_detector.detectMultiScale(gray) 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 > 70: global warningtime warningtime += 1 if warningtime > 100: # 发送警报 # warning() print("陌生人") warningtime = 0 cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1) else: # print(ids - 1) cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1) cv2.imshow('result', img) # print('bug:',ids) def name(): path = './data/jm/' # names = [] imagePaths = [os.path.join(path, f) for f in os.listdir(path)] print('数据排列:', imagePaths) for imagePath in imagePaths: name = str(os.path.split(imagePath)[1].split('.', 2)[1]) names.append(name) #print(names) # , cv.cvtColor(img, cv.COLOR_BGR2GRAY) # 读取视频 # cap = cv2.VideoCapture('1.mp4') # 读取摄像头 cap = cv2.VideoCapture(0) name() print(names) # names.reverse() # 队列反转 # print(names) while True: flag, frame = cap.read() if not flag: break face_detect_demo(frame) if ord(' ') == cv2.waitKey(10): break cv2.destroyAllWindows() cap.release()
10.录入人脸数据
import cv2 #摄像头 cap=cv2.VideoCapture(0) falg = 1 num = 1 while(cap.isOpened()): ret_flag,Vshow = cap.read() cv2.imshow("Capture_Test",Vshow) k = cv2.waitKey(1) & 0xFF if k == ord('s'): cv2.imwrite("./data/jm/"+str(num)+".lixian"+".jpg",Vshow) print("success to save"+str(num)+".jpg") print("--------------------") num +=1 elif k == ord(' '): break #释放摄像头 cap.release() #释放内存 cv2.destroyAllWindows()
调用网络视频
import cv2 class CaptureVideo(object): def net_video(self): # 获取网络视频流 cam = cv2.VideoCapture("rtmp://58.200.131.2:1935/livetv/cctv2") while cam.isOpened(): sucess, frame = cam.read() cv2.imshow("Network", frame) cv2.waitKey(1) if __name__ == "__main__": capture_video = CaptureVideo() capture_video.net_video()