首页 > 解决方案 > 在图像上显示掩码检测器时出错

问题描述

大家好,我可以问一下为什么面部哈尔级联在 Kaggle 中不起作用?它显示了图像,但不会覆盖所谓的掩码检测方块。我正在制作关于检测图像上戴或不戴口罩的人脸的项目。然而,我总是遇到面部haarcascade的问题。输入也在 Kaggle 的目录中。我是 kaggle 的新用户,最近才发现它,这就是我对这个平台不太熟悉的原因。我也是 python 新手,呵呵,我需要知道为什么它不起作用。谢谢!

import tensorflow as tf
import keras
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import load_img
import numpy as np
import argparse
import cv2
import os
import matplotlib.pyplot as plt
%matplotlib inline
model = tf.keras.models.load_model("../input/my-modelh5/my_model.h5")
images=['../input/example/example_01.png', '../input/example/example_02.png','../input/example/example_03.png' ]
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')
img = images[0]    # Add path here
    
img = plt.imread(img,format='8UC1')
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray = np.array(gray, dtype='uint8')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

# Draw the rectangle around each face
for (x, y, w, h) in faces:

    face = img[y:y+h, x:x+w]
    face = cv2.resize(face, (224, 224))
    face = img_to_array(face)
    face = preprocess_input(face)
    face = np.expand_dims(face, axis=0)
    (mask, withoutMask) = model.predict(face)[0]
    mask = mask*100
    withoutMask = withoutMask*100
    
    font = cv2.FONT_HERSHEY_SIMPLEX
    
    # Getting Text Size in pixel
    print("Image Width: " , w)
    textSize = cv2.getTextSize(text="No Mask: " + str("%.2f" % round(mask, 2)), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, thickness=3)
    print("Text Width: " , textSize[0][0])
    
    if mask > withoutMask:
        cv2.putText(img,
                    text = "Mask: " + str("%.2f" % round(mask, 2)),
                    org = (x-5,y-15),
                    fontFace=font,
                    fontScale = (2*w)/textSize[0][0],
                    color = (0, 255, 0),
                    thickness = 3,
                    lineType = cv2.LINE_AA)
        cv2.rectangle(img, (x, y), (x+w, y+h), (0,255,0), 5)
    else:
        cv2.putText(img,
                    text = "No Mask: " + str("%.2f" % round(withoutMask, 2)),
                    org = (x-5,y-15),
                    fontFace=font,
                    fontScale = (1.8*w)/textSize[0][0],
                    color = (255, 0, 0),
                    thickness = 3,
                    lineType = cv2.LINE_AA)
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 5)

# Display
plt.imshow(img)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

标签: python

解决方案


推荐阅读