CV算法:反向投影(Back Projection)

参考资料:
选取ROI
Back Projection
给出ROI的直方图分布,主要要归一化,把每个柱子当作对应强度出现的概率,然后在测试图像中,每个像素点的强度去查询前面的概率(0~1),然后作为新图像的强度(也可以乘以255得到整形强度值)。
程序流程,BGR->HSV->Hue
然后取出ROI进行生成直方图数据
然后再backproject在整个Hue上面。
程序运行后,框一个框,然后回车或者是空格。
对魔方的识别还不是很好,每种颜色都要自定义一些参数,然后会有稍微一些混淆。肤色识别的很好。

CV算法:反向投影(Back Projection)_第1张图片

CV算法:反向投影(Back Projection)_第2张图片

CV算法:反向投影(Back Projection)_第3张图片

代码:


string windowName = "back project";
const int maxSlideValue = 255;
int slideValue;
Mat src, hsv, hue, ROI, hist, imBackProject;
int threashold = 10;
int histSize = 10;

void on_trackbar1(int slideValue, void* imBackProject){
    threashold = slideValue;

    //分析ROI的直方图分布
    float hue_range[] = { 0, 255 };
    const float* ranges = { hue_range };
    calcHist(&ROI, 1, 0, Mat(), hist, 1, &histSize, &ranges);
    normalize(hist, hist, 0, 255, NORM_MINMAX);

    calcBackProject(&hue, 1, 0, hist, *(Mat *)imBackProject, &ranges, 1, true);

    Mat imBackProject2;
    threshold(*(Mat *)imBackProject, imBackProject2, threashold, 255, THRESH_BINARY);
    imshow(windowName, imBackProject2);
}


void on_trackbar2(int slideValue, void* imBackProject) {
    histSize = max(slideValue,2);

    //分析ROI的直方图分布
    float hue_range[] = { 0, 255 };
    const float* ranges = { hue_range };
    calcHist(&ROI, 1, 0, Mat(), hist, 1, &histSize, &ranges);
    normalize(hist, hist, 0, 255, NORM_MINMAX);

    calcBackProject(&hue, 1, 0, hist, *(Mat *)imBackProject, &ranges, 1, true);

    Mat imBackProject2;
    threshold(*(Mat *)imBackProject, imBackProject2, threashold, 255, THRESH_BINARY);
    imshow(windowName, imBackProject2);
}


int main() {


    //转化为HSV
    //src = imread("4cube.png");
    src = imread("hands.jpg");
    cvtColor(src, hsv, COLOR_BGR2HSV);
    hue.create(hsv.size(), hsv.depth());
    int ch[] = { 0, 0 };
    mixChannels(&hsv, 1, &hue, 1, ch, 1);

    //while (1) {
        //选出ROI
        Rect r = selectROI(src);
        ROI = hue(r);



        namedWindow(windowName);
        createTrackbar("阈值化的阈值", windowName, &slideValue, maxSlideValue, on_trackbar1, &imBackProject);
        createTrackbar("直方图纵轴个数", windowName, &slideValue, maxSlideValue, on_trackbar2, &imBackProject);
        on_trackbar1(threashold, &imBackProject);
        on_trackbar2(histSize, &imBackProject);

        //threshold(imBackProject, imBackProject, 30, 255, THRESH_BINARY);
        //imshow(windowName, imBackProject);
    //}

END:
    waitKey(0);
    system("pause");
    return 0;
}

你可能感兴趣的:(CV算法:反向投影(Back Projection))