Python实用记录(七):通过retinaface对CASIA-WebFace人脸数据集进行清洗,并把错误图路径放入txt文档

简介: 使用RetinaFace模型对CASIA-WebFace人脸数据集进行清洗,并将无法检测到人脸的图片路径记录到txt文档中。

由于这些数据集是通过爬虫直接在网上下载的,有很多错误的图,需要把它们找出来进行删除。
1:使用RetinaFace对给定的图片做人脸检测,对于提取不到landmark/boundingbox的图片逐个做分析。
2:将图像缩小送进网络训练发现很多都可以检测出来了,其实retinaface对尺度比较小的图片效果会好很多

https://download.csdn.net/download/m0_51004308/19513502?spm=1001.2014.3001.5501这是基于python版本的整个完整的数据集清洗(包括retainface模型文件,运行操作也非常简单,只需要把你的数据集路径加入其中就行。有详细注释,需要可以了解)

import numpy as np
import torch
import cv2
from retinaface.detector import RetinafaceDetector, RetinafaceDetector_dnn
from align_faces import align_process

class retinaface():
    def __init__(self, device = 'cuda', align=False):
        self.retinaface = RetinafaceDetector(device=device)
        self.align = align
    def detect(self, srcimg):
        bounding_boxes, landmarks = self.retinaface.detect_faces(srcimg)
        drawimg, face_rois = srcimg.copy(), []
        for i in range(bounding_boxes.shape[0]):
            # score = bounding_boxes[i,4]
            x1, y1, x2, y2 = (bounding_boxes[i, :4]).astype(np.int32)
            cv2.rectangle(drawimg, (x1, y1), (x2, y2), (0, 0, 255), thickness=2)
            face_roi = srcimg[y1:y2, x1:x2]
            landmark = landmarks[i, :].reshape((2, 5)).T
            if self.align:
                face_roi = align_process(srcimg, bounding_boxes[i, :4], landmark, (224, 224))
            landmark = landmark.astype(np.int32)
            for j in range(5):
                cv2.circle(drawimg, (landmark[j, 0], landmark[j, 1]), 2, (0, 255, 0), thickness=-1)
                # cv2.putText(drawimg, str(j), (landmark[j, 0], landmark[j, 1] + 12), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255))
            face_rois.append(face_roi)
        return drawimg, face_rois
    def get_face(self, srcimg):
        bounding_boxes, landmarks = self.retinaface.detect_faces(srcimg)
        boxs, face_rois = [], []
        for i in range(bounding_boxes.shape[0]):
            # score = bounding_boxes[i,4]
            box = (bounding_boxes[i, :4]).astype(np.int32).tolist()
            face_roi = srcimg[box[1]:box[3], box[0]:box[2]]
            landmark = landmarks[i, :].reshape((2, 5)).T
            if self.align:
                face_roi = align_process(srcimg, bounding_boxes[i, :4], landmark, (224, 224))
            box.extend(landmark.astype(np.int32).ravel().tolist())
            boxs.append(tuple(box))
            face_rois.append(face_roi)
        return boxs, face_rois

class retinaface_dnn():
    def __init__(self, align=False):
        self.net = RetinafaceDetector_dnn()
        self.align = align

    def detect(self, srcimg):
        bounding_boxes, landmarks = self.net.detect_faces(srcimg)
        drawimg, face_rois = srcimg.copy(), []
        for i in range(bounding_boxes.shape[0]):
            # score = bounding_boxes[i,4]
            x1, y1, x2, y2 = (bounding_boxes[i, :4]).astype(np.int32)
            cv2.rectangle(drawimg, (x1, y1), (x2, y2), (0, 0, 255), thickness=2)
            face_roi = srcimg[y1:y2, x1:x2]
            landmark = landmarks[i, :].reshape((2, 5)).T
            if self.align:
                face_roi = align_process(srcimg, bounding_boxes[i, :4], landmark, (224, 224))
            landmark = landmark.astype(np.int32)
            for j in range(5):
                cv2.circle(drawimg, (landmark[j, 0], landmark[j, 1]), 2, (0, 255, 0), thickness=-1)
                # cv2.putText(drawimg, str(j), (landmark[j, 0], landmark[j, 1] + 12), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255))
            face_rois.append(face_roi)
        return drawimg, face_rois

    def get_face(self, srcimg):
        bounding_boxes, landmarks = self.net.detect_faces(srcimg)
        boxs, face_rois = [], []
        for i in range(bounding_boxes.shape[0]):
            # score = bounding_boxes[i,4]
            box = (bounding_boxes[i, :4]).astype(np.int32).tolist()
            face_roi = srcimg[box[1]:box[3], box[0]:box[2]]
            landmark = landmarks[i, :].reshape((2, 5)).T
            if self.align:
                face_roi = align_process(srcimg, bounding_boxes[i, :4], landmark, (224, 224))
            box.extend(landmark.astype(np.int32).ravel().tolist())
            boxs.append(tuple(box))
            face_rois.append(face_roi)
        return boxs, face_rois

if __name__ == "__main__":
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    # retinaface_detect = retinaface(device=device, align=True)
    retinaface_detect = retinaface_dnn(align=True)
    ###dnn版本和pytorch版本的一个区别是: pytorch版本的输入图片不做resize就进入到网络里,而dnn版本的输入图片要resize到固定尺寸的,
    ###输入不同,因此对这两个版本的输出不做比较
    import os,sys


    f = open('error.txt', 'w')
    imgroot = '/home/lqs/Documents/arcface-pytorch-master/data/CASIA-WebFace/'
    #imgroot = '/home/lqs/Documents/arcface-pytorch-master/data/902_Pic_Fea/'
    im=0
    dirlist = os.listdir(imgroot)  ### imgroot里有多个文件夹,每个文件夹存放着一个人物的多个肖像照,文件夹名称是人名
    for i, name in enumerate(dirlist):
        sys.stdout.write("\rRun person{0}-{1}, name:{2}\n".format(i,len(dirlist),name))
        sys.stdout.flush()
        imgdir = os.path.join(imgroot, name)
        imglist = os.listdir(imgdir)
        for imgname in imglist:
            imapath=os.path.join(imgdir, imgname)
            srcimg = cv2.imread(imapath)
            drawimg, face_rois = retinaface_detect.detect(srcimg)
            # cv2.imshow('face_rois',face_rois)
            # cv2.waitKey(0)
            #print(len(face_rois))
            if len(face_rois)==0:
                f.write(imapath + '\n')
                im+=1
                print('the error pic',imapath)
    print('the totle error pic  {} 个'.format(im))
    f = open("/home/lqs/Documents/arcface-pytorch-master/data/error.txt", "r")
    lines = f.readlines()  # 读取全部内容
    print('the len of txt is {}'.format(len(lines)))
目录
相关文章
|
23天前
|
Python
用python3快速读取30G+的txt文件
这篇文章介绍了如何使用Python分块读取大文件(如30G+的txt文件),通过设置每次读取的块大小来处理大型文本文件,以减少内存消耗并提高处理效率。
56 14
|
2月前
|
计算机视觉 Windows Python
windows下使用python + opencv读取含有中文路径的图片 和 把图片数据保存到含有中文的路径下
在Windows系统中,直接使用`cv2.imread()`和`cv2.imwrite()`处理含中文路径的图像文件时会遇到问题。读取时会返回空数据,保存时则无法正确保存至目标目录。为解决这些问题,可以使用`cv2.imdecode()`结合`np.fromfile()`来读取图像,并使用`cv2.imencode()`结合`tofile()`方法来保存图像至含中文的路径。这种方法有效避免了路径编码问题,确保图像处理流程顺畅进行。
206 1
|
12天前
|
安全 Python
Python 高级编程:高效读取 txt 文件的技巧与实践
在 Python 中,读取 txt 文件是常见操作。本文介绍了使用 `with` 语句自动管理文件资源、逐行读取文件、读取特定字节范围内容、处理编码问题以及使用缓冲读取提高性能等高级方法,确保代码高效且安全。通过这些技巧,你可以更灵活地处理文件内容,并避免资源泄漏等问题。原文链接:https://www.wodianping.com/app/2024-10/44183.html
40 18
|
1天前
|
Python
Python实用记录(六):如何打开txt文档并删除指定绝对路径下图片
这篇文章介绍了如何使用Python打开txt文档,删除文档中指定路径的图片,并提供了一段示例代码来展示这一过程。
8 1
|
1天前
|
Python
Python实用记录(四):os模块-去后缀或者改后缀/指定目录下图片或者子目录图片写入txt/csv
本文介绍了如何使用Python的os模块来操作文件,包括更改文件后缀、分割文件路径和后缀、将指定目录下的所有图片写入txt文档,以及将指定目录下所有子目录中的图片写入csv文档,并为每个子目录分配一个标签。
6 1
|
3天前
|
人工智能 开发者 Python
python读取word文档 | AI应用开发
在RAG系统中,构建知识库时需读取多种外部文档,其中Word文档较为常见。本文介绍如何使用`python-docx`库读取Word文档(.docx格式)中的标题、段落、表格和图片等内容。首先通过`pip install python-docx`安装库,然后利用提供的接口提取所需信息。尽管该库功能强大,但在识别标题样式时需自定义逻辑,并且仅提供图片的URI而非直接加载。示例代码展示了读取文本、识别标题、读取表格及获取图片URI的方法。【10月更文挑战第2天】
17 2
|
9天前
|
数据可视化 数据挖掘 大数据
Python 数据分析入门:从零开始处理数据集
Python 数据分析入门:从零开始处理数据集
|
7天前
|
数据采集 机器学习/深度学习 存储
使用 Python 清洗日志数据
使用 Python 清洗日志数据
14 2
|
9天前
|
IDE 开发工具 iOS开发
Python编程案例:查找指定文件大小的文件并输出路径
Python编程案例:查找指定文件大小的文件并输出路径
15 3
|
18天前
|
存储 数据采集 关系型数据库
Python之文档数据存储
Python之文档数据存储
27 2