效果图

源代码

import os
import sys
import cv2
import numpy as npdef normalize(X, low, high, dtype=None):"""Normalizes a given array in X to a value between low and high."""X = np.asarray(X)minX, maxX = np.min(X), np.max(X)# normalize to [0...1].X = X - float(minX)X = X / float((maxX - minX))# scale to [low...high].X = X * (high-low)X = X + lowif dtype is None:return np.asarray(X)return np.asarray(X, dtype=dtype)def read_images(path, sz=None):"""Reads the images in a given folder, resizes images on the fly if size is given.Args:path: Path to a folder with subfolders representing the subjects (persons).sz: A tuple with the size ResizesReturns:A list [X,y]X: The images, which is a Python list of numpy arrays.y: The corresponding labels (the unique number of the subject, person) in a Python list."""c = 0X,y = [], []for dirname, dirnames, filenames in os.walk(path):for subdirname in dirnames:subject_path = os.path.join(dirname, subdirname)for filename in os.listdir(subject_path):try:if (filename == ".directory"):continuefilepath = os.path.join(subject_path, filename)im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE)if (im is None):print ("image " + filepath + " is none")else:print (filepath)# resize to given size (if given)if (sz is not None):im = cv2.resize(im, (200, 200))X.append(np.asarray(im, dtype=np.uint8))y.append(c)# except IOError, (errno, strerror):#     print ("I/O error({0}): {1}".format(errno, strerror))except:print ("Unexpected error:", sys.exc_info()[0])raiseprint (c)c = c+1# print (X) #2017-6-11 addprint (y)return [X,y]def face_rec():names = ['fanshengmei']if len(sys.argv) < 2:print ("USAGE: facerec_demo.py </path/to/images> [</path/to/store/images/at>]")sys.exit()[X,y] = read_images(sys.argv[1])y = np.asarray(y, dtype=np.int32)if len(sys.argv) == 3:out_dir = sys.argv[2]model = cv2.face.createEigenFaceRecognizer()model.train(np.asarray(X), np.asarray(y))camera = cv2.VideoCapture("2.mp4")face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_alt2.xml')while (True):read, img = camera.read()# faces = face_cascade.detectMultiScale(img, 1.3, 5)faces = face_cascade.detectMultiScale(img, 1.4, 5)for (x, y, w, h) in faces:img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# print(gray)roi = gray[x:x+w, y:y+h]# print(roi)try:roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR)print (roi.shape)params = model.predict(roi)print ("Label: %s, Confidence: %.2f" % (params[0], params[1]))cv2.putText(img, names[params[0]], (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)if (params[0] == 0):cv2.imwrite('face_rec.jpg', img)except:continuecv2.imshow("camera", img)if cv2.waitKey(1000 // 12) & 0xff == ord("q"):breakcv2.destroyAllWindows()if __name__ == "__main__":face_rec()def original():# This is where we write the images, if an output_dir is given# in command line:out_dir = Nonenames = ['Joe', 'Jane', 'Jack']# jm->Joe、 jb->Jane、sw->Jack# You'll need at least a path to your image data, please see# the tutorial coming with this source code on how to prepare# your image data:if len(sys.argv) < 2:print ("USAGE: facerec_demo.py </path/to/images> [</path/to/store/images/at>]")sys.exit()# Now read in the image data. This must be a valid path![X,y] = read_images(sys.argv[1])# Convert labels to 32bit integers. This is a workaround for 64bit machines,# because the labels will truncated else. This will be fixed in code as# soon as possible, so Python users don't need to know about this.# Thanks to Leo Dirac for reporting:y = np.asarray(y, dtype=np.int32)# If a out_dir is given, set it:if len(sys.argv) == 3:out_dir = sys.argv[2]# Create the Eigenfaces model. We are going to use the default# parameters for this simple example, please read the documentation# for thresholding:#model = cv2.face.createLBPHFaceRecognizer()model = cv2.face.createEigenFaceRecognizer()# Read# Learn the model. Remember our function returns Python lists,# so we use np.asarray to turn them into NumPy lists to make# the OpenCV wrapper happy:model.train(np.asarray(X), np.asarray(y))# We now get a prediction from the model! In reality you# should always use unseen images for testing your model.# But so many people were confused, when I sliced an image# off in the C++ version, so I am just using an image we# have trained with.## model.predict is going to return the predicted label and# the associated confidence:camera = cv2.VideoCapture(0)face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')while (True):read, img = camera.read()faces = face_cascade.detectMultiScale(img, 1.3, 5)for (x, y, w, h) in faces:img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)roi = gray[x:x+w, y:y+h]roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR)print (roi.shape)params = model.predict(roi)print ("Label: %s, Confidence: %.2f" % (params[0], params[1]))cv2.putText(img, names[params[0]], (x,y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 3)cv2.imshow("camera", img)if cv2.waitKey(1000 / 12) & 0xff == ord("q"):break[p_label, p_confidence] = model.predict(np.asarray(X[0]))# Print it:print ("Predicted label = %d (confidence=%.2f)" % (p_label, p_confidence))# Cool! Finally we'll plot the Eigenfaces, because that's# what most people read in the papers are keen to see.## Just like in C++ you have access to all model internal# data, because the cv::FaceRecognizer is a cv::Algorithm.## You can see the available parameters with getParams():print (model.getParams())# Now let's get some data:mean = model.getMat("mean")eigenvectors = model.getMat("eigenvectors")# We'll save the mean, by first normalizing it:mean_norm = normalize(mean, 0, 255, dtype=np.uint8)mean_resized = mean_norm.reshape(X[0].shape)if out_dir is None:cv2.imshow("mean", mean_resized)else:cv2.imwrite("%s/mean.png" % (out_dir), mean_resized)# Turn the first (at most) 16 eigenvectors into grayscale# images. You could also use cv::normalize here, but sticking# to NumPy is much easier for now.# Note: eigenvectors are stored by column:# for i in xrange(min(len(X), 16)):for i in range(min(len(X), 16)):eigenvector_i = eigenvectors[:,i].reshape(X[0].shape)eigenvector_i_norm = normalize(eigenvector_i, 0, 255, dtype=np.uint8)# Show or save the images:if out_dir is None:cv2.imshow("%s/eigenface_%d" % (out_dir,i), eigenvector_i_norm)else:cv2.imwrite("%s/eigenface_%d.png" % (out_dir,i), eigenvector_i_norm)# Show the images:if out_dir is None:cv2.waitKey(0)cv2.destroyAllWindows()

完整项目文档下载

http://download.csdn.net/download/wyx100/9867602

程序运行方法

http://blog.csdn.net/wyx100/article/details/73017614

开发环境快速搭建(30分钟)

http://blog.csdn.net/wyx100/article/details/73008528

人脸检测和识别 源代码 下载-opencv3+python3.6完整实战项目源代码 识别视频《欢乐颂》中人物相关推荐

  1. python3项目源代码下载_人脸检测和识别 源代码 下载-opencv3+python3.6完整实战项目源代码 识别视频《欢乐颂》中人物,-opencv3《欢乐颂》...

    人脸检测和识别 源代码 下载-opencv3+python3.6完整实战项目源代码 识别视频<欢乐颂>中人物,-opencv3<欢乐颂> 效果图 源代码import os im ...

  2. 人脸检测和识别(中文标记)完整项目源代码(基于深度学习+python3.6+dlib+PIL+CNN+(tensorflow、keras)10分钟实现 区分欢乐颂中人物详细图文教程和完整项目代码)

    转载请注明:https://blog.csdn.net/wyx100/article/details/80428424 效果展示 未完待续... 环境配置 win7sp1 python         ...

  3. 最强六大开源轻量级人脸检测项目分析 | 附打包下载

    随着深度学习的兴起,工业界和学术界越来越多的使用基于深度学习的方法,而不是传统的基于模板匹配,纹理提取或者像素积分图等方法.因为人脸检测本身并不属于特别复杂的任务,因此轻量级的深度学习模型即可满足该任 ...

  4. 20个Python 3实战项目源代码,助你快速提升编程技能!

    仅仅"读"代码是无法带来任何实际收益的,就像"读书"一样,如果你在阅读时不思考,那么你很可能在三个月后忘记了大部分内容.真正有效的方法是去"试&quo ...

  5. android源代码下载AE 文字样式,阅读Android framework源代码方式

    阅读Android framework源代码方式 点击标题下「蓝色微信名」可快速关注 阅读源代码的方式有很多,这里只讲其中的两种方式. 一.AndroidXRef(强烈推荐) 这种方式速度快,操作简单 ...

  6. 使用MATLAB控制笔记本电脑的摄像头,并进行实时人脸检测和识别

    FPGA教程目录 MATLAB教程目录 ----------------------------------------------------------------------- 目录 一.理论基 ...

  7. OpenCV4Android开发实录(2): 使用OpenCV3.4.1库实现人脸检测

    OpenCV4Android开发实录(2): 使用OpenCV3.3.0库实现人脸检测 转载请声明出处:http://write.blog.csdn.net/postedit/78992490 Ope ...

  8. Qt之OpenCV人脸检测以及识别

    简介 最近做了一个人脸检测以及识别的程序,很多的文章都有比较详细的叙述,可以自行查找.但是个人觉得大部分文章都太细致了以至于初学者无法快速领会主干(不是否认质量),是侧重点问题.所以结合我遇到了一些问 ...

  9. AI人脸检测和人脸识别是一个概念吗?有什么区别?

    人脸检测 - 也称为面部检测 - 是一种基于人工智能 (AI) 的计算机技术,用于在数字图像中查找和识别人脸.人脸检测技术可应用于各个领域--包括安全.生物识别.执法.娱乐和个人安全--以提供对人员的 ...

最新文章

  1. L1-056 猜数字 (结构体解决)
  2. 喝不起奶茶,咱就为奶茶店开发个会员积分收银系统
  3. 什么是企业的固定资产全寿命周期管理
  4. Android开发之Java基础面试题抽象类和接口的区别
  5. 关于重写equals()与hashCode()
  6. 嘉年华回顾丨李圣陶带你了解阿里巴巴智能化运维的奥秘
  7. Web后端学习笔记 Flask (5) 数据库
  8. Python学习:图形界面设计01
  9. 为什么setTimeout(fn,0)有时有用?
  10. 洛谷P1156 垃圾陷阱【线性dp】
  11. js基础知识汇总01
  12. Axure RP9使用指南
  13. html向下的箭头符号,向下的箭头符号
  14. 读书笔记《数学建模算法与应用》第4-6章
  15. php 半角全角,php字符串处理之全角半角转换
  16. Teardrop原始套接字编程
  17. https网络编程——DNS域名解析获取IP地址
  18. 需求分析挑战之旅(疯狂的订餐系统)(5)——领导“突发奇想”
  19. day007-列表和字典
  20. 苹果电脑拷贝文件到u盘很慢_ChronoSync v4.9.1 一款文件资料数据云同步备份工具...

热门文章

  1. 计算机网络原理综合考核,计算机网络原理考试重点
  2. 音乐:什么样的音乐对人“有帮助”
  3. C++设置音量合成器应用音量
  4. Redis数据操作(redis入门)
  5. html飞机动画,html5 canvas纸飞机跟随鼠标飞行动画
  6. window.open(ulr)被浏览器拦截解决
  7. 2022年同济大学计算机考研复试分数线
  8. Origin学生版的获取方法和安装方法
  9. 计算机网络原理【四】之 网络层
  10. Chrome 浏览器全球大翻车?让 20 多亿用户无网可上