CELLON Kart(Tracking)

CELLON Kart HSV Tracking(1)

박민혀기 2023. 7. 1. 00:36
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main() {
    VideoCapture cap = VideoCapture(0);
    if (!cap.isOpened()) {
        cout << "Could't load camera" << endl;
        return -1;
    }

    cap.set(CAP_PROP_FRAME_WIDTH, cap.get(CAP_PROP_FRAME_WIDTH) / 2);
    cap.set(CAP_PROP_FRAME_HEIGHT, cap.get(CAP_PROP_FRAME_HEIGHT) / 2);

    int channels[] = { 0, 1 };  // 히스토그램에는 Hue와 Saturation 채널만 사용합니다.
    int histSize[] = { 180, 256 };  // Hue와 Saturation 채널의 빈(bin) 개수
    float hueRange[] = { 0, 180 };  // Hue 값 범위
    float satRange[] = { 0, 256 };  // Saturation 값 범위
    const float* ranges[] = { hueRange, satRange };

    Mat frame, hsv_frame, ROI_frame;
    Rect2d roi_pt;
    Scalar meanHSV;
    Scalar lowerHSV(-60, -60, -60);
    Scalar upperHSV(60, 60, 60);
    namedWindow("frame");

    while (1) {
        cap >> frame;
        if (frame.empty()) {
            cout << "Could't load frame" << endl;
            return -1;
        }

        if (!roi_pt.empty()) {
            Mat mask;
            Mat result;
            cvtColor(frame, hsv_frame, COLOR_BGR2HSV);
            inRange(hsv_frame, lowerHSV, upperHSV, mask);

            bitwise_and(frame, frame, result, mask);
            imshow("result", result);
        }
        else {
            putText(frame, "Hit the Space to set target to track", Point(10, 30), FONT_HERSHEY_SIMPLEX,
                1, Scalar(0, 0, 255), 1);
        }

        int key = waitKey(33);
        if (key == 27) break;
        else if (key == 32) {
            roi_pt = selectROI("frame", frame, false, false);
            cvtColor(frame, hsv_frame, COLOR_BGR2HSV);
            ROI_frame = hsv_frame(roi_pt).clone();
            meanHSV = mean(ROI_frame);
            cout << meanHSV << endl;
            
            lowerHSV = meanHSV + lowerHSV;
            upperHSV = meanHSV + upperHSV;

            imshow("ROI_frame", ROI_frame);
        }

        imshow("frame", frame);
    }

    cap.release();
    destroyAllWindows();
    return 0;
}