Pytorch Facenet MTCNN图像输出

2024-04-18 14:28:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用两种方法在python中使用facenet Pytork(https://github.com/timesler/facenet-pytorch)做一个人脸识别应用程序

第一种方法 代码-

resnet = InceptionResnetV1(pretrained='vggface2').eval()
mtcnn = MTCNN(image_size=96)

img = Image.open(image_path)
image_prep = mtcnn(img)
plt.figure()
plt.axis('off')
plt.imshow(image_prep.permute(1, 2, 0))
if image_prep is not None:
  image_embedding = resnet(image_prep.unsqueeze(0))

在这段代码中,我从给定的图像中提取人脸,并获得用于识别人脸的512种编码

在本例中,我使用了两个不同的面,并绘制了面之间的距离

        a.jpg       b.jpg
a.jpg   0.000000    1.142466
b.jpg   1.142466    0.000000

它工作得很好

第二种方法 代码-

 img = Image.open(image)
 boxes, probs = mtcnn.detect(img) # Gives the coordinates of the face in the given image
 face = img.crop((boxes[0][0], boxes[0][1], boxes[0][2], boxes[0][3])) # Cropping the face
 plt.figure()
 plt.imshow(face)
 pil_to_tensor = transforms.ToTensor()(face).unsqueeze_(0) # Converting to tensor type
 image_embedding = resnet(pil_to_tensor)

在这段代码中,我通常先获得面坐标,然后是嵌入的坐标。两个面之间的距离-

        a.jpg       b.jpg
a.jpg   0.000000    0.631094
b.jpg   0.631094    0.000000

在第一种方法中,我直接将图像送入mtcnn,得到了更好的结果,两个面之间的距离大于1.0。 在第二种方法中,我使用mtcnn.detect()获取面坐标,从给定的图像中裁剪面,然后馈送到resnet。此方法使两个不同面之间的距离更小

然后,我通过在输入resnet之前绘制结果(面),找到了第一种方法比第二种方法性能好的原因

在第二种方法中,我通过使用mtcnn.detect()裁剪面来填充与输入图像(清晰图像)中给定的面相同的面

但是,在第1种方法中,我直接向mtcnn(img)输入,它返回黑暗中的面张量,而不是输入图像中的面张量。这个较暗的图像不是清晰的图像(眼睛周围的区域较暗,我用很多照片测试过),无法清晰地看到眼睛。这就是原因,第一种方法显示两个面之间的距离更大

我的疑问是,为什么mtcnn在黑暗中返回张量,如何解决它,在这个问题上帮助我

谢谢


Tags: the方法代码图像image距离imgplt