Search code examples
c++opencvyolov5

OpenCV rectangles not clearing after updating an image


I'm working with YoloV5 using object detection with OpenCv, my problem is that after I draw the bounding boxes of the detected objects they don't clear after the image source gets updated. Here is the relevant code with the issue:

    while (true) {
        //Loading Image

        cv::Mat target = getMat(hWND);
        
        cv::Mat frame;
        
        cv::cvtColor(target, target, cv::COLOR_RGB2BGR);
        cv::cvtColor(target, target, cv::COLOR_BGR2RGB);
        
        target.copyTo(frame);

        //Fps Counter
        frames++; //increments frames
        time(&current_time); //sets current_time
        
        //Object detection
        detect(frame, net, output, class_list);

        int detections = output.size();

        //Drawing boxes and text
        for (int i = 0; i < detections; ++i) {

            auto detection = output[i];
            auto box = detection.box;
            auto classId = detection.class_id;
            const auto color = colors[classId % colors.size()];
            cv::rectangle(frame, box, color, 3);

            cv::rectangle(frame, cv::Point(box.x, box.y - 20), cv::Point(box.x + box.width, box.y), color, cv::FILLED);
            cv::putText(frame, class_list[classId].c_str(), cv::Point(box.x, box.y - 5), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
        }

        cv::imshow("output", frame);
        cv::waitKey(30);

        //Fps counter continuation
        if (difftime(current_time, begin_time) >= 1.0) //if one second has passed since the loop started
        {
            printf("Frames: %.21f\n", frames); //print the frames run through in one second
            frames = 0; //reset frames
            time(&begin_time); //resets begin_time
        }

        //Break loop with key press
        if (_kbhit()) {
            key = _getch();
            if (key == KEY_W) {
                std::cout << "closing..." << std::endl;
                cv::destroyAllWindows();
                break;
            }

        }

    }

enter image description here enter image description here

I'm not really sure how to fix this, been working a lot of hours today, so I'm pretty burnt out at the moment, so any suggestions are appreciated!


Solution

  • Turns out that I just had to "empty" the output vector, it was accumulating all of the detections and drawing them every time at the for loop!