Home > Net >  Python Opencv draw rectangle from smaller frame
Python Opencv draw rectangle from smaller frame

Time:02-02

I am currently working on a face detection algorithm using MTCNN.

With the below code, I am able to show the frame containing my face:

`def run_detection(fast_mtcnn):
    frames = []
    frames_processed = 0
    faces_detected = 0
    batch_size = 60
    start = time.time()

    cap = cv2.VideoCapture(0)

    while True:
        __, frame = cap.read()
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frames.append(frame)

        faces = fast_mtcnn(frames)

        frames_processed  = len(frames)
        faces_detected  = len(faces)
        frames = []
        if len(faces) > 0:
            for face in faces:
                cv2.imshow('frame',face)
                
        print(
            f'Frames per second: {frames_processed / (time.time() - start):.3f},',
            f'faces detected: {faces_detected}\r',
            end=''
        )
        if cv2.waitKey(1) &0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()`

FYI, the cv2.imshow('frame',face) is just for me to put some value there as I would like to get its bouding box.

Which looks something like this(please forgive my silly looking face):

enter image description here

This I just to show that it is detecting the face and its taking out the frames relating to my face.

What my challenge is, is how to take the smaller frame face (containing my face) and get the edge coordinates of it to draw a bounding box for each person in the frame.

What I tried is the following:

cv2.rectangle(frame,
                          (face[0], face[1]),
                          (face[0] face[2], face[1]   face[3]),
                          (0,155,255),
                          2)

Which i assume is completely wrong.

CodePudding user response:

The solution will depend on how the points are returned by the face detection system which can vary depending on the library you use. In this case the detected face contains the following information x, y, w, h = face where x and y is a point, w is the width of the bounding box, and h is the height.

Hence you can draw a rectangle of the face as follows:

cv2.rectangle(frame, (x, y), (x   w, y   h), (0, 0, 255), 2)
  • Related