摄像头为ip摄像头各大应用商店下载
实现手机做电脑摄像头并实现人脸识别
import cv2
def CatchPICFromVideo():
cv2.namedWindow("image", 0)
# qcv2.resizeWindow("image", 1600, 900) # 设置长和宽
# 视频来源,可以来自一段已存好的视频,手机摄像头
video = "http://admin:admin@你的ip地址:8081/" # 此处@后的ipv4 地址需要改为app提供的地址 前面密码可以自己在手机IP摄像头修改上修改
cap = cv2.VideoCapture(video)
# 告诉OpenCV使用人脸识别分类器
data_path = "haarcascade_frontalface_default.xml"
classifier = cv2.CascadeClassifier(data_path)
# 识别出人脸后要画的边框的颜色,RGB格式
color = (0, 255, 0)
num = 0
while cap.isOpened():
ok, frame1 = cap.read() # 读取一帧数据
scale_percent = 50 # percent of original size 缩小到原来25%
width = int(frame1.shape[1] * scale_percent / 100)
height = int(frame1.shape[0] * scale_percent / 100)
dim = (width, height)
frame = cv2.resize(frame1, dim, interpolation=cv2.INTER_AREA)
if not ok:
break
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 将当前桢图像转换成灰度图像
# 人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数
faceReacts = classifier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
print(faceReacts)
if len(faceReacts) > 0: # 大于0则检测到人脸
for faceRect in faceReacts: # 单独框出每一张人脸
x, y, w, h = faceRect
# 将当前帧保存为图片
# img_name = '%s/%d.jpg ' %(path_name, num)
# image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
# cv2.iwrite(img_name, image)
num += 1
# if num > catch_pic_num: # 如果超过指定最大保存数量退出循环
# break
# 画出矩形框
cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
# 显示当前捕捉到了多少人脸图片了,这样站在那里被拍摄时心里有个数,不用两眼一抹黑傻等着
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, 'num:%d' % num, (x + 30, y + 30), font, 1, (255, 0, 255), 4)
if num > 100:
num = 0
# 超过指定最大保存数量结束程序
# if num > catch_pic_num:
# break
# 显示图像q
cv2.imshow("image", frame)
c = cv2.waitKey(1)
if c & 0xFF == ord('q'):
break
# 释放摄像头并销毁所有窗口
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
CatchPICFromVideo()