Commit 3f669a00 authored by tonyfun's avatar tonyfun

Initial commit

parents
*.avi
camera
face
.idea
# The default ``config.py``
def set_prefs(prefs):
"""This function is called before opening the project"""
# Specify which files and folders to ignore in the project.
# Changes to ignored resources are not added to the history and
# VCSs. Also they are not returned in `Project.get_files()`.
# Note that ``?`` and ``*`` match all characters but slashes.
# '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
# 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
# '.svn': matches 'pkg/.svn' and all of its children
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
'.hg', '.svn', '_svn', '.git']
# Specifies which files should be considered python files. It is
# useful when you have scripts inside your project. Only files
# ending with ``.py`` are considered to be python files by
# default.
#prefs['python_files'] = ['*.py']
# Custom source folders: By default rope searches the project
# for finding source folders (folders that should be searched
# for finding modules). You can add paths to that list. Note
# that rope guesses project source folders correctly most of the
# time; use this if you have any problems.
# The folders should be relative to project root and use '/' for
# separating folders regardless of the platform rope is running on.
# 'src/my_source_folder' for instance.
#prefs.add('source_folders', 'src')
# You can extend python path for looking up modules
#prefs.add('python_path', '~/python/')
# Should rope save object information or not.
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False
# If `True`, rope analyzes each module when it is being saved.
prefs['automatic_soa'] = True
# The depth of calls to follow in static object analysis
prefs['soa_followed_calls'] = 0
# If `False` when running modules or unit tests "dynamic object
# analysis" is turned off. This makes them much faster.
prefs['perform_doa'] = True
# Rope can check the validity of its object DB when running.
prefs['validate_objectdb'] = True
# How many undos to hold?
prefs['max_history_items'] = 32
# Shows whether to save history across sessions.
prefs['save_history'] = True
prefs['compress_history'] = False
# Set the number spaces used for indenting. According to
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
# unit-tests use 4 spaces it is more reliable, too.
prefs['indent_size'] = 4
# Builtin and c-extension modules that are allowed to be imported
# and inspected by rope.
prefs['extension_modules'] = []
# Add all standard c-extensions to extension_modules list.
prefs['import_dynload_stdmods'] = True
# If `True` modules with syntax errors are considered to be empty.
# The default value is `False`; When `False` syntax errors raise
# `rope.base.exceptions.ModuleSyntaxError` exception.
prefs['ignore_syntax_errors'] = False
# If `True`, rope ignores unresolvable imports. Otherwise, they
# appear in the importing namespace.
prefs['ignore_bad_imports'] = False
def project_opened(project):
"""This function is called after opening the project"""
# Do whatever you like here!
}q(Utest]qUimgqaUshutil]q(UcopyfileqUignore_patternsqUcopytreeqUget_archive_formatsqU copyfileobjq Uregister_archive_formatq
Ucopymodeq U make_archiveq Umoveq Uunregister_archive_formatqUrmtreeqUErrorqUcopyqU ExecErrorqUcopy2qUSpecialFileErrorqUcopystatqU WindowsErrorqeUos]q(Upopen4qUexecleqUpopen3qUSEEK_CURqUspawnlpqUexeclpqUenvironqUspawnvpqUspawnlq Uexecvpq!Umakedirsq"Ulinesepq#UP_WAITq$Uspawnvq%Uspawnveq&Uexecvpeq'Uunsetenvq(USEEK_SETq)Ugetenvq*Upopen2q+Uwalkq,Uspawnleq-Uexeclq.Unameq/USEEK_ENDq0Uspawnlpeq1U P_NOWAITOq2UP_NOWAITq3U
removedirsq4Urenamesq5Uspawnvpeq6Uexeclpeq7eUdatetime]q8(U timedeltaq9UMAXYEARq:Udateq;U datetime_CAPIq<Utzinfoq=Utimeq>UMINYEARq?Udatetimeq@eu.
\ No newline at end of file
]q(]q]qe.
\ No newline at end of file
}q.
\ No newline at end of file
# opencv-face
基于python-opencv调用摄像头的实时人脸检测和识别
cap_1.jpg

51.7 KB

#coding=utf-8
import cv2
import cv2.cv as cv
import numpy as np
import math
def detect(img, cascade):
'''detectMultiScale函数中smallImg表示的是要检测的输入图像为smallImg,
faces表示检测到的人脸目标序列,1.3表示每次图像尺寸减小的比例为1.3,
4表示每一个目标至少要被检测到3次才算是真的目标(因为周围的像素和不同的窗口大小都可以检测到人脸),
CV_HAAR_SCALE_IMAGE表示不是缩放分类器来检测,而是缩放图像,Size(20, 20)为目标的最小最大尺寸'''
rects = cascade.detectMultiScale(img, scaleFactor=1.3,
minNeighbors=5, minSize=(30, 30), flags = cv.CV_HAAR_SCALE_IMAGE)
if len(rects) == 0:
return []
rects[:,2:] += rects[:,:2]
print rects
return rects
#在img上绘制矩形
def draw_rects(img, rects, color):
for x1, y1, x2, y2 in rects:
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
def rotate_about_center(src, angle, scale=1.):
w = src.shape[1]
h = src.shape[0]
rangle = np.deg2rad(angle) # angle in radians
# now calculate new image width and height
nw = (abs(np.sin(rangle) * h) + abs(np.cos(rangle) * w)) * scale
nh = (abs(np.cos(rangle) * h) + abs(np.sin(rangle) * w)) * scale
# ask OpenCV for the rotation matrix
rot_mat = cv2.getRotationMatrix2D((nw * 0.5, nh * 0.5), angle, scale)
# calculate the move from the old center to the new center combined
# with the rotation
rot_move = np.dot(rot_mat, np.array([(nw - w) * 0.5, (nh - h) * 0.5, 0]))
# the move only affects the translation, so update the translation
# part of the transform
rot_mat[0, 2] += rot_move[0]
rot_mat[1, 2] += rot_move[1]
return cv2.warpAffine(src, rot_mat, (int(math.ceil(nw)), int(math.ceil(nh))), flags=cv2.INTER_LANCZOS4)
class FaceDetect(object):
def __init__(self):
#正脸
self.front_fn = 'haarcascades/haarcascade_frontalface_alt.xml'
# cascade_fn = 'lbpcascades/lbpcascade_frontalface.xml'
#侧脸
self.profile_fn = 'haarcascades/haarcascade_profileface.xml'
# cascade_fn = 'lbpcascades/lbpcascade_profileface.xml'
#读取分类器,CascadeClassifier下面有一个detectMultiScale方法来得到矩形
self.frontCascade = cv2.CascadeClassifier(self.front_fn)
self.profileCascade = cv2.CascadeClassifier(self.profile_fn)
return
def detect(self, img):
"""
:param img:{numpy}
:return:
"""
#vis为img副本
vis = img.copy()
#转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#直方图均衡处理
gray = cv2.equalizeHist(gray)
#通过分类器得到rects
rects = detect(gray, self.frontCascade)
if len(rects) == 0:
#侧脸检测
rects = detect(gray, self.profileCascade)
if len(rects) == 0:
#镜像 在侧脸检测
gray = cv2.flip(gray, 1)
rects = detect(gray, self.profileCascade)
vis = cv2.flip(vis, 1)
result = []
#画矩形
draw_rects(vis, rects, (0, 255, 0))
if len(rects) != 0:
for x1, y1, x2, y2 in rects:
result.append(vis[y1:y2, x1:x2])
else:
result.append(vis)
return result
if __name__ == '__main__':
img = cv2.imread("face/1.jpg")
model = FaceDetect()
vis = model.detect(img)
cv2.imshow('facedetect', vis[0])
cv2.waitKey(0)
cv2.destroyAllWindows()
\ No newline at end of file
File added
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import os
import os.path
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
# cap.set(3, 1080);
cap.set(4, 720);
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_eye.xml')
while(1):
# get a frame
ret, img = cap.read()
# show a frame
# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# ret2, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(frame, contours, -1, (0, 0, 255), 3)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# img = cv2.rectangle(img, (0, 0), (10, 10), (255, 0, 0), 2)
imgOrigin = cv2.rectangle(img, (0, 0), (10, 10), (255, 0, 0), 2)
for (x, y, w, h) in faces:
cv2.imwrite("cap_1.jpg", img);
img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# roi_gray = gray[y:y + h, x:x + w]
# roi_color = img[y:y + h, x:x + w]
# eyes = eye_cascade.detectMultiScale(roi_gray)
cv2.imshow("capture", img)
time.sleep(0.1)
k = cv2.waitKey(1) & 0xFF;
if k == ord('a'):
print( cap.get(3));
print( cap.get(4));
# print(cap.get(4));
if k == ord('s'):
print( cap.get(3));
print( cap.get(4));
# print(cap.get(4));
elif k == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
# for (x, y, w, h) in faces:
# img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# roi_gray = gray[y:y + h, x:x + w]
# roi_color = img[y:y + h, x:x + w]
# eyes = eye_cascade.detectMultiScale(roi_gray)
#
# for (ex, ey, ew, eh) in eyes:
# cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
# cv2.imshow('img', img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
__author__ = 'yinchuandong'
import cv2
from face import FaceDetect
model = FaceDetect()
capture = cv2.VideoCapture(0)
size = (int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),
int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
# video = cv2.VideoWriter("VideoTest.avi", cv2.cv.CV_FOURCC('I', '4', '2', '0'), 30, size)
# print capture.isOpened()
num = 0
while True:
ret, img = capture.read()
imgArr = model.detect(img)
for img in imgArr:
# video.write(img)
cv2.imshow('Video', img)
key = cv2.waitKey(1)
cv2.imwrite('camera/%s.jpg' % (str(num)), img)
num = num + 1
if key == ord('q'):
break
# video.release()
capture.release()
cv2.destroyAllWindows()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment