Home>

This is a code that uses Opencv and dlib to detect the mouth and cut out and save it.

File "1122.py", line 56, in<module>
    main ()
  File "1122.py", line 38, in main
    frame, roi = face_shape_detector_dlib (frame)
  File "1122.py", line 10, in face_shape_detector_dlib
    dets, scores, idx = detector.run (img_rgb, 0)
NameError: name 'detector' is not defined


Will give an error.

Here is the code. I want to be able to compile it.
Thank you.

import cv2
import dlib
import numpy as np
import imutils
from imutils import face_utils
def face_shape_detector_dlib (img):
    img_rgb = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)
    # frontal_face_detector class returns rectangle, score, and sub-detector results
    dets, scores, idx = detector.run (img_rgb, 0)
    if len (dets)>0:
        for i, rect in enumerate (dets):
            shape = predictor (img_rgb, rect)
            shape = face_utils.shape_to_np (shape)
            clone = img.copy ()
            cv2.putText (clone, "mouth", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
            # write landmark to image
            for (x, y) in shape [48:68]:
                cv2.circle (clone, (x, y), 1, (0, 0, 255), -1)
            # Get cropped image (ROI) of the part specified by shape
            (x, y, w, h) = cv2.boundingRect (np.array ([shape [48:68]])) #Extract only the mouth part
            roi = img [y: y + h, x: x + w]
            roi = cv2.resize (roi, (100,100))
        return clone, roi
    else:
        return img, None
def main ():
    predictor_path = "./shape_predictor_68_face_landmarks.dat"
    predictor = dlib.shape_predictor (predictor_path)
    detector = dlib.get_frontal_face_detector ()
    cap = cv2.VideoCapture (0)
    count = 0
    while True:
        ret, frame = cap.read ()
        frame = imutils.resize (frame, width = 500)
        frame, roi = face_shape_detector_dlib (frame)
        cv2.imshow ('img', frame)
        if roi is not None:
            cv2.imshow ('roi', roi)
        else:
            cv2.destroyWindow ('roi')
        c = cv2.waitKey (1)
        if c == 27: Press #ESC to close the window
            break
        if c == 32: Save as #space
            count + = 1
            cv2.imwrite ('./ filename% 03.f'% (count) + '. jpg', roi) # 001 ~ Save as sequential number
            print ('save done')
    cap.release ()
    cv2.destroyAllWindows ()
if __name__ == '__main__':
    main ()
  • Answer # 1

    Variables defined within a function can only be referenced within that function.
    Therefore, the variable called detector defined in main () cannot be accessed from face_shape_detector_dlib ().
    How about modifying it so that it is passed as an argument as follows?

    Definition

    -def face_shape_detector_dlib (img, detector):
    + def face_shape_detector_dlib (img):

    Caller

    -face_shape_detector_dlib (img, detector):
    + face_shape_detector_dlib (img):
    Additional
    import cv2
    import dlib
    import numpy as np
    import imutils
    from imutils import face_utils
    def face_shape_detector_dlib (img):
        img_rgb = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)
        # frontal_face_detector class returns rectangle, score, and sub-detector results
        dets, scores, idx = detector.run (img_rgb, 0)
        if len (dets)>0:
            for i, rect in enumerate (dets):
                shape = predictor (img_rgb, rect)
                shape = face_utils.shape_to_np (shape)
                clone = img.copy ()
                cv2.putText (clone, "mouth", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
                # write landmark to image
                for (x, y) in shape [48:68]:
                    cv2.circle (clone, (x, y), 1, (0, 0, 255), -1)
                # Get cropped image (ROI) of the part specified by shape
                (x, y, w, h) = cv2.boundingRect (np.array ([shape [48:68]])) #Extract only the mouth part
                roi = img [y: y + h, x: x + w]
                roi = cv2.resize (roi, (100,100))
            return clone, roi
        else:
            return img, None
    predictor_path = "./shape_predictor_68_face_landmarks.dat"
    predictor = dlib.shape_predictor (predictor_path)detector = dlib.get_frontal_face_detector ()
    cap = cv2.VideoCapture (0)
    count = 0
    while True:
        ret, frame = cap.read ()
        frame = imutils.resize (frame, width = 500)
        frame, roi = face_shape_detector_dlib (frame)
        cv2.imshow ('img', frame)
        if roi is not None:
            cv2.imshow ('roi', roi)
        else:
            cv2.destroyWindow ('roi')
        c = cv2.waitKey (1)
        if c == 27: Press #ESC to close the window
            break
        if c == 32: Save as #space
            count + = 1
            cv2.imwrite ('./ filename% 03.f'% (count) + '. jpg', roi) # 001 ~ Save as sequential number
            print ('save done')
    cap.release ()
    cv2.destroyAllWindows ()

  • Answer # 2

    As the error message says, 'detector' doesn't exist
    Let's make it somewhere

  • Answer # 3

    import cv2
    import dlib
    import numpy as np
    import imutils
    from imutils import face_utils
    detector = dlib.get_frontal_face_detector ()
    predictor = dlib.shape_predictor ("shape_predictor_68_face_landmarks.dat")
    def face_shape_detector_dlib (img, detector):
        img_rgb = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)
        # frontal_face_detector class returns rectangle, score, and sub-detector results
        dets, scores, idx = detector.run (img_rgb, 0)
        if len (dets)>0:
            for i, rect in enumerate (dets):
                shape = predictor (img_rgb, rect)
                shape = face_utils.shape_to_np (shape)
                clone = img.copy ()cv2.putText (clone, "mouth", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
                # write landmark to image
                for (x, y) in shape [48:68]:
                    cv2.circle (clone, (x, y), 1, (0, 0, 255), -1)
                # Get cropped image (ROI) of the part specified by shape
                (x, y, w, h) = cv2.boundingRect (np.array ([shape [48:68]])) #Extract only the mouth part
                roi = img [y: y + h, x: x + w]
                roi = cv2.resize (roi, (80,50))
            return clone, roi
        else:
            return img, None
    def main ():
        predictor_path = "./shape_predictor_68_face_landmarks.dat"
        predictor = dlib.shape_predictor (predictor_path)
        detector = dlib.get_frontal_face_detector ()
        cap = cv2.VideoCapture (0)
        count = 0
        while True:
            ret, frame = cap.read ()
            frame = imutils.resize (frame, width = 500)
            frame, roi = face_shape_detector_dlib (frame, detector)
            cv2.imshow ('img', frame)
            if roi is not None:
                cv2.imshow ('roi', roi)
            else:
                cv2.destroyWindow ('roi')
            c = cv2.waitKey (1)
            if c == 27: Press #ESC to close the window
                break
            if c == 32: Save as #space
                count + = 1
                cv2.imwrite ('./ filename% 03.f'% (count) + '. jpg', roi) # 001 ~ Save as sequential number
                print ('save done')
        cap.release ()
        cv2.destroyAllWindows ()
    if __name__ == '__main__':
        main ()