欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 基于opencv[python]的人脸检测

基于opencv[python]的人脸检测

2024/10/24 7:26:25 来源:https://blog.csdn.net/m0_65963495/article/details/140699084  浏览:    关键词:基于opencv[python]的人脸检测

1 图片爬虫

这里的代码转载自:http://t.csdnimg.cn/T4R4F

# 获取图片数据
import os.path
import fake_useragent
import requests
from lxml import etree# UA伪装
head = {"User-Agent": fake_useragent.UserAgent().random}pic_name = 0
def request_pic(url):# 发送请求response = requests.get(url, headers=head)# 获取想要的数据res_text = response.text# 数据解析tree = etree.HTML(res_text)li_list = tree.xpath("//div[@class='slist']/ul/li")for li in li_list:# 图片的urlimg_url = "https://pic.netbian.com" + "".join(li.xpath("./a/img/@src"))# 发送请求img_response = requests.get(img_url, headers=head)# 获取想要的数据img_content = img_response.contentglobal pic_namewith open(f"./picLib/{pic_name}.jpg", "wb") as fp:fp.write(img_content)pic_name += 1if __name__ == '__main__':# 创建存放照片的文件夹if not os.path.exists("./picLib"):os.mkdir("./picLib")# 网站的urlurl = "https://pic.netbian.com/4kdongman/"request_pic(url)for i in range(1,10):next_url = f"https://pic.netbian.com/4kmeinv/index_{i}.html"request_pic(next_url)

         结果如图1-1所示:

图 1-1  

2 基于opencv自带分类器的人脸检测 

import cv2  
import os  
import matplotlib.pyplot as plt  # 定义人脸检测器的路径  
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')  # 设置图片文件夹路径  
folder_path = 'picLib'  # 设置要显示的图像数量  
num_to_display = 5  # 例如,只显示前4张图像  # 创建一个图形和子图  
fig, axs = plt.subplots(1, num_to_display, figsize=(15, 5))  # 遍历文件夹中的前几张图片  
for i in range(num_to_display):  file_name = f'{i}.jpg'  image_path = os.path.join(folder_path, file_name)  # 读取图片  img = cv2.imread(image_path)  if img is None:  print(f"Error loading image {file_name}")  continue  # 转换为灰度图  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 检测人脸  faces = face_cascade.detectMultiScale(gray, 1.3, 5)  # 在原图上绘制矩形框  for (x, y, w, h) in faces:  cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)  # 注意:OpenCV 图像是BGR,而Matplotlib 期望的是RGB,因此我们需要转换颜色通道  img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 显示图像  axs[i].imshow(img_rgb)  axs[i].axis('off')  # 关闭坐标轴  # 显示图形  
plt.show()  

        运行结果如图2-1所示:

图 2-1 

        从这里可以清晰看到有1/3的图像没有成功检测到,后面我试试用Faster R-CNN模型,不过需要标注,数据量也大,这里先试着玩玩呗。 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com