#-*- coding: utf-8 -*-
import ft2
import os
import sys
import time
import cv2
import numpy as np
def 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 + low
if 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 Resizes
Returns:
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 = 0
X,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"):
continue
filepath = 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])
raise
print (c)
c = c+1
# print (X) #2017-6-11 add
print (y)
return [X,y]
def face_rec():
names = ['蒋欣 饰演 樊胜美']
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")
#camera = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_alt2.xml')
while (True):
read, img = camera.read()
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)
#中文设置
color = (0, 255, 0) # Green
pos = (x-5, y-30)
text_size = 20
ft = ft2.put_chinese_text('msyh.ttf') # 加载字体微软雅黑
image = ft.draw_text(img, pos, names[params[0]], text_size, color)#中文输出
if (params[0] == 0):
cv2.imwrite('face_rec.jpg', img)
except:
continue
cv2.imshow("camera", image)
if cv2.waitKey(1000 // 12) & 0xff == ord("q"):
break
cv2.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 = None
names = ['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]))
ft = ft2.put_chinese_text('msyh.ttf')
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)
没有合适的资源?快使用搜索试试~ 我知道了~
机器学习人脸检测和识别(中文标记姓名) python+opencv+freetype 图文教程和项目源代码
共77个文件
pgm:50个
xml:19个
py:2个
5星 · 超过95%的资源 需积分: 50 337 下载量 27 浏览量
2017-07-24
13:57:48
上传
评论 19
收藏 22.08MB ZIP 举报
温馨提示
机器学习人脸检测和识别(中文标记姓名) python+opencv+freetype 图文教程和项目源代码 图文教程 http://blog.csdn.net/wyx100/article/details/75675644
资源推荐
资源详情
资源评论
收起资源包目录
chFaceRec.zip (77个子文件)
chFaceRec
cascades
haarcascade_fullbody.xml 466KB
haarcascade_profileface.xml 809KB
haarcascade_upperbody.xml 767KB
haarcascade_russian_plate_number.xml 74KB
haarcascade_lowerbody.xml 386KB
haarcascade_eye.xml 333KB
haarcascade_frontalface_alt_tree.xml 2.56MB
haarcascade_smile.xml 184KB
haarcascade_frontalface_default.xml 908KB
haarcascade_righteye_2splits.xml 192KB
haarcascade_licence_plate_rus_16stages.xml 47KB
haarcascade_frontalface_alt.xml 661KB
haarcascade_frontalface_alt2.xml 528KB
haarcascade_eye_tree_eyeglasses.xml 588KB
haarcascade_lefteye_2splits.xml 191KB
data
at
fs
46.pgm 39KB
5.pgm 39KB
24.pgm 39KB
32.pgm 39KB
42.pgm 39KB
27.pgm 39KB
10.pgm 39KB
2.pgm 39KB
40.pgm 39KB
1.pgm 39KB
47.pgm 39KB
13.pgm 39KB
20.pgm 39KB
48.pgm 39KB
28.pgm 39KB
45.pgm 39KB
43.pgm 39KB
38.pgm 39KB
11.pgm 39KB
21.pgm 39KB
4.pgm 39KB
33.pgm 39KB
15.pgm 39KB
41.pgm 39KB
6.pgm 39KB
50.pgm 39KB
29.pgm 39KB
12.pgm 39KB
3.pgm 39KB
34.pgm 39KB
17.pgm 39KB
31.pgm 39KB
9.pgm 39KB
26.pgm 39KB
0.pgm 39KB
36.pgm 39KB
23.pgm 39KB
44.pgm 39KB
35.pgm 39KB
49.pgm 39KB
39.pgm 39KB
30.pgm 39KB
8.pgm 39KB
19.pgm 39KB
22.pgm 39KB
25.pgm 39KB
18.pgm 39KB
7.pgm 39KB
37.pgm 39KB
16.pgm 39KB
faceshls.csv 590B
msyh.ttf 20.76MB
ft2.py 4KB
2.mp4 6.64MB
.idea
misc.xml 226B
workspace.xml 23KB
chFaceRec.iml 459B
inspectionProfiles
profiles_settings.xml 228B
modules.xml 270B
videohls_rec.py 8KB
face_rec.jpg 115KB
ft2.pyc 4KB
共 77 条
- 1
wyx100
- 粉丝: 1328
- 资源: 149
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 白色个性风格的3D博客网站模板下载.rar
- 白色个性风格的时尚纹身艺术网站模板下载.zip
- 白色极简的设计师简历模板下载.zip
- 白色个性风格的网络科技CSS网站模板.zip
- 白色简单的商务企业网站模板下载.rar
- 白色极致简洁的画册vi设计公司网页模板下载.zip
- 白色简单风格的商务企业网站模板下载.zip
- 白色简单精致的汽车行业网站模板下载.zip
- 白色简洁布局的云托管网站模板下载.zip
- 白色简洁大气的个人博客网站模板下载.rar
- 白色简洁大气风的博客网站模板下载.zip
- 白色简洁大气效果的智能机器人企业网站模板下载.zip
- 白色简洁的工作室企业网页模板下载.zip
- 白色简洁的IT数码产品网站模板下载.rar
- 白色简洁的服务企业网站模板下载.zip
- 白色简洁的商务企业网页模板下载.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页