使用python实现图片的人脸检测功能

本博客介绍了一个使用Python3实现的面部识别演示项目,通过OpenCV库进行面部检测,并从网络下载图片进行测试。代码中包含了异常处理,确保了程序的稳定运行。

Demo主要使用了Python3的类库实现,有下载失败的欢迎联系,注释处分别为可识别和不可识别的两张网络图片,Xml文件可以点击下载

import cv2
import urllib.request
import time
def cbk(a, b, c):
        per = 100.0 * a * b / c
        if per > 100:
            per = 100
        print('%.2f%%' % per)

def faceDetect(img,face_cascade):
    temp = False
    try:
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    
        faces = face_cascade.detectMultiScale(gray,1.3,5)
        
        for(x,y,w,h) in faces:
            temp = True
            
    except Exception as e:
        print ('Exception: ', e)
    return temp
    
def readImg(urlStr):
    try:
        return urllib.request.urlopen(urlStr).read()
    except Exception as e:
        print ('Exception: ', e)
        return "error"


def main():
    # 这个指向本地的xml配置文件
    face_cascade = cv2.CascadeClassifier("G:\Java\python\haarcascades\haarcascade_frontalface_default.xml")
    # https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3443139237,286953275&fm=26&gp=0.jpg
    # https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543575837&di=78f2d4dc61f33874f7decd4b3d2c75ba&imgtype=jpg&er=1&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fzhidao%2Fwh%253D450%252C600%2Fsign%3D977c525998510fb3784c7f93ec03e4a3%2F5fdf8db1cb1349547892f484504e9258d0094a45.jpg
    urlstr = "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3443139237,286953275&fm=26&gp=0.jpg";
    print("exec============="+urlstr)
    content=readImg(urlstr)
    if content == "error":
        print("未读取到图片")
    # 图片保存地址
    path = "G:\\Java\\python\\test.jpg";
    with open(path,'wb') as ftemp :
        ftemp.write(content)
        
        frame = cv2.imread(path)
        isPeople = faceDetect(frame,face_cascade)
        
        if isPeople :
            print("true")
        else:
            print("false")
    
main()

这里是执行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码先觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值