zoukankan      html  css  js  c++  java
  • Python cv2库(人脸检测)

    根据访问图片识别

     # coding:utf-8

    import sys
    import math

    import cv2

    # 待检测的图片路径

    imagepath = r'l.png'

    face_cascade = cv2.CascadeClassifier(r'./haarcascade_frontalface_default.xml')

    # 读取图片

    image = cv2.imread(imagepath)

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 探测图片中的人脸

    faces = face_cascade.detectMultiScale(

    gray,

    scaleFactor=1.15,

    minNeighbors=5,

    minSize=(5, 5),

    flags=cv2.CASCADE_SCALE_IMAGE

    )

    print ("发现{0}个人脸!".format(len(faces)))

    for (x, y, w, h) in faces:

    #cv2.rectangle(image,(x,y),(x+w,y+w),(0,255,0),2)
    green = (0, 255, 0)
    cv2.rectangle(image, (x, y), (x + w, y + h), green, 2)
    #cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

    #cv2.circle(image, ((x + x + w) // 2, (y + y + h) // 2), w // 2, (0, 255, 0), 2)

    cv2.imshow("Find Faces!", image)

    cv2.waitKey(0)

    haarcascade_frontalface_default.xml文件下载:

    链接:https://pan.baidu.com/s/1puL055J6CWa6dXks79UYkg  密码:r4sy

    开启摄像头检测

    # coding:utf-8

    import cv2
    import numpy as np

    # Load the face cascade file 按照自己的文件位置加入,如果是下载的原书的程序包那就不用改了
    face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')

    # Check if the face cascade file has been loaded
    if face_cascade.empty():
    raise IOError('Unable to load the face cascade classifier xml file')

    # Initialize the video capture object
    cap = cv2.VideoCapture(0)

    # Define the scaling factor
    scaling_factor = 0.5

    # Loop until you hit the Esc key
    while True:
    # Capture the current frame and resize it
    ret, frame = cap.read()
    frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor,
    interpolation=cv2.INTER_AREA)

    # Convert to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Run the face detector on the grayscale image
    face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)

    # Draw rectangles on the image
    for (x, y, w, h) in face_rects:
    cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)

    # Display the image
    cv2.imshow('Face Detector', frame)

    # Check if Esc key has been pressed
    c = cv2.waitKey(1)
    if c == 27:
    break

    # Release the video capture object and close all windows
    cap.release()
    cv2.destroyAllWindows()

  • 相关阅读:
    PowerDesigner如何设置字段为自增长
    Tab标签
    过滤数据集DataTable方法
    时间复杂度计算方法
    Oracle字符函数
    ASP.NET 应用程序生命周期概述
    在同一个DataSet中添加多个DataTable
    谈SQL SERVER数据库中的索引
    Abstract 与 Vitrual 用法
    活动图与流程图的区别
  • 原文地址:https://www.cnblogs.com/chaihy/p/10118868.html
Copyright © 2011-2022 走看看