一些基础知识
import cv2
def Basic_Knowledge():
"""
imread 读取一张图片文件,第二个参数默认为1(代表为彩色图片)
imshow 用于展示一张图片,第一个参数为图片名,第二个参数为已经读取过的图片文件
resize 可以重新规划图片的大小,第一个参数为已经读取过的图片文件,第二个参数为图片的长和高
img.shape 代表图片的参数
cv2.waitKey 代表等待用户的输入
cv2.destroyAllWindows 代表关闭所有窗口
:return:null
"""
img = cv2.imread('../static/b9.png', 1)
new_img = cv2.resize(img, (int(img.shape[1]*5), int(img.shape[0]*5)))
cv2.imshow('smile_face', new_img)
cv2.waitKey(2000)
cv2.destroyAllWindows()
Basic_Knowledge()
识别图片中的人脸
import cv2
face_cascade = cv2.CascadeClassifier("../static/haarcascade_frontalface_default.xml")
img = cv2.imread('../static/liuyifei.png')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.05, minNeighbors=5)
for x, y, w, h in faces:
"""
在 img上创建矩形, 左上顶点坐标为 (x, y), 右下顶点坐标为 (x+w, y+h)
矩形颜色为 (0, 255, 0), 矩形线条粗度为 3px
"""
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3)
resized = cv2.resize(img, (int(img.shape[1]/2), int(img.shape[0]/2)))
cv2.imshow("liuyifei", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
识别自己设备中的人脸
import cv2
video = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier("../static/haarcascade_frontalface_default.xml")
index = 1
while True:
index += 1
check, frame = video.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=5)
if index % 3 == 0:
print('发现了%s个人脸' % len(faces))
for x, y, w, h in faces:
img = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
cv2.imshow('Capturing', frame)
if cv2.waitKey(1) == 113:
break
print(index)
video.release()
cv2.destroyAllWindows()
识别视频中的人脸
import cv2
video = cv2.VideoCapture('../static/九龄|冬日jk女友|当她眼角带笑.mp4')
face_cascade = cv2.CascadeClassifier("../static/haarcascade_frontalface_default.xml")
index = 1
while True:
index += 1
check, frame = video.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=5, minSize=(50, 50))
if index % 3 == 0:
print('发现了%s个人脸' % len(faces))
for x, y, w, h in faces:
img = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 5)
new_frame = cv2.resize(frame, (int(frame.shape[1]/3), int(frame.shape[0]/3)))
cv2.imshow('Capturing', new_frame)
if cv2.waitKey(1) == 113:
break
print(index)
video.release()
cv2.destroyAllWindows()