python使用opencv摄像头人脸识别案例

main方法运行,运行后自动打开摄像头,按住鼠标中间追踪人脸。

import cv2 as cv
import pyautogui as ui
"""封装鼠标检测人脸"""
model_bin = "C:/zk/work/code/python/opencv4/opencv_tutorial_data-master/models/face_detector/opencv_face_detector_uint8.pb"
config_text = "C:/zk/work/code/python/opencv4/opencv_tutorial_data-master/models/face_detector/opencv_face_detector.pbtxt";
net = cv.dnn.readNetFromTensorflow(model=model_bin, config=config_text)
cap = cv.VideoCapture(0)
def testvodeo():
    net = cv.dnn.readNetFromTensorflow(model=model_bin, config=config_text)
    # 打开摄像头
    # cap = cv.VideoCapture(0)

    # 创建窗口并绑定鼠标回调函数
    cv.namedWindow('Video')
    cv.setMouseCallback('Video', mouse_callback)

    while True:
        # 读取摄像头图像
        ret, frame = cap.read()

        # 显示摄像头图像
        cv.imshow('Video', frame)

        # 按下ESC键退出程序
        if cv.waitKey(1) == 27:
            break



    # 释放摄像头
    cap.release()
    cv.destroyAllWindows()

# 定义鼠标回调函数
def mouse_callback(event, x, y, flags, param):
    if event == cv.EVENT_MBUTTONDOWN:
        print('Left button clicked at: ({}, {})'.format(x, y))
        while True:
            ret, frame = cap.read()
            h, w, c = frame.shape  #
            if ret is not True:
                break
            # NCHW
            blob = cv.dnn.blobFromImage(frame, 1.0, (300, 300), (104.0, 177.0, 123.0), False, False)  # 获取人脸样本数据
            net.setInput(blob)
            outs = net.forward()  # 1x1xNx7
            for detection in outs[0, 0, :, :]:
                score = float(detection[2])
                if score > 0.5:  # 阈值越接近1越像人脸
                    left = detection[3] * w
                    top = detection[4] * h
                    right = detection[5] * w
                    bottom = detection[6] * h
                    ui.moveTo(left + 280, top + 380, duration=0.001)
                    cv.rectangle(frame, (int(left), int(top)), (int(right), int(bottom)), (0, 0, 255), 2, 8, 0)
            cv.imshow("Video", frame)
            c = cv.waitKey(1)
            if c == 27:
                break
    elif event == cv.EVENT_MBUTTONUP:
        print('Right button clicked at: ({}, {})'.format(x, y))
        while True:
            # 读取摄像头图像
            ret, frame = cap.read()

            # 显示摄像头图像
            cv.imshow('Video', frame)

            # 按下ESC键退出程序
            if cv.waitKey(1) == 27:
                break

if __name__=='__main__':
    testvodeo()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值