2013-05-01 50 views
1

请看看下面的代码如何进行图像反投影?

#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp> 
#include <opencv2/imgproc/imgproc.hpp> 
#include <iostream> 

using namespace std; 
using namespace cv; 

MatND detectContent(Mat image); 

MatND getHistogram(Mat image); 

int main() 
{ 
    Mat image; 


    try 
    { 
     image = imread("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg",CV_LOAD_IMAGE_GRAYSCALE); 
     cv::rectangle(image,Rect(670,150,60,60),Scalar(255)); 

     if(!image.data) 
     { 
      throw 1; 
     } 
    } 
    catch(int a) 
    { 
     cout << "Image is unable to read" << endl; 
    } 


    //Following will show the selected location of the image for the histogam 
    namedWindow("Image Selected Location"); 
    imshow("Image Selected Location",image); 


    //Following will display the edites image 
    namedWindow("Image"); 
    imshow("Image",image); 
    imshow("Image",detectContent(image)); 

    waitKey(0); 
    return 0; 
} 

MatND detectContent(Mat image) 
{ 


    //Regiion of interest 
    Mat imageROI = image(Rect(900,40,60,100)); 

    //Get the histogram 
    MatND hist = getHistogram(imageROI); 

    //Normalizing the histogram 
    cv::normalize(hist,hist,1.0); 


    //Backprojecting the image 
    MatND result; 

    float *rangeArray; 
    rangeArray[0] = 0.0; 
    rangeArray[1] = 255.0; 

    const float *rans[1]; 
    rans[0] = rangeArray; 

    int *channels[1]; 
    channels[0] = 0; 

    cv::calcBackProject(&image,1,0,hist,result,rans,255.0); 

    return result; 
} 

MatND getHistogram(Mat image) 
{ 
    MatND hist; 

    int histSize[1];//Number of bins 
    float hRanges[2];//Max and Min pixel values 
    const float *ranges[1]; 
    int channels[1];//Only one channel will be used 

    histSize[0] = 256; 

    hRanges[0] = 0.0; 
    hRanges[1] = 255.0; 

    ranges[0] = hRanges; 

    channels[0] = 0; 

    cv::calcHist(&image,1,channels,Mat(),hist,1,histSize,ranges); 

    return hist; 
} 

当你运行该代码时,“背投影的”图像是100%的黑色!另一幅名为“图像选定位置”的图像将在图像的选定位置绘制一个白色矩形以显示直方图。我将在下面显示

enter image description here

为什么我的背投影图像是100%黑色的形象?请帮忙!

编辑

至少有人可以尝试这种在他们的机器,让我知道结果?

+0

你确定它是100%黑色吗?可能是一个非常低的价值。此外,反投影对于颜色直方图非常有用。 – 2013-05-01 11:55:18

+0

@AbidRahmanK:谢谢你的回复,对不起,我的评论推迟了。是的,它是纯黑的。如果你是一个Windows用户,你可以轻松地测试这个案例,因为企鹅图像可以在你的“样本图像”文件夹中找到。请帮忙。 – 2013-05-01 14:38:50

回答

4

我只是测试你张贴在OS X(以下结果)的代码,它工作正常,有两个小的修正。 Backprojected penguins

detectContent()detectContent()您声明float *rangeArray;没有初始化它,然后立即解除引用它。这是一个错误。相反,将其声明为:

float rangeArray[2]; 

其次,提供给cv::calcBackProject()的范围是排他的。这意味着你应该,如果你希望包括全系列8位值的行

rangeArray[1] = 255.0; 

改变

rangeArray[1] = 256.0; 

。否则,任何值为255的像素将不会包含在直方图中。

此外,中的行imshow("Image",image);是不必要的。要显示的图像立即被detectContent()的结果替换为下一行。

+0

太棒了!万分感谢!伟大的解释帮助很大!再次感谢我的+1! – 2013-05-01 18:19:42

1

尝试在这条线的范围设置为1

CV :: calcBackProject(&图像,1,0,HIST,结果,失败者,255.0);

,并设置统一的标志

我得到这个从here