Why do I get bad results with calcBackProject in opencv?

Viewed 29

I create a project to reduce noise in the target image. I want to do something on Histograms, so I use calcHist to get the histogram of the image. When I use calcBackProject to recover images, the results are very different from the source image that I can't understand. The results show that the histogram of the two images is significant differences. Are there some problems with histogram processing?

By the way, my OpenCV version is 4.5.0.

enter image description here

enter image description here

int main()
{
Mat src = imread("./newpaperback.jpg");
imshow("src", src);

Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
imshow("gray", gray);

const int channels[] = {0};
Mat hist;
int dims = 1;
const int histSize[] = {256};;
float granges[] = {0, 256};
const float* ranges[] = { granges };

calcHist(&gray, 1, channels, Mat(), hist, dims, histSize, ranges, true, false);

int hist_height = 256;
Mat hist_image = Mat::zeros(hist_height, hist_height * 2, CV_8UC3);
double max_val;
minMaxLoc(hist, 0, &max_val, 0, 0);
for(int i = 0; i < hist_height; i++)
{
    float bin_val = hist.at<float>(i);
    segment[i] = bin_val * hist_height / max_val;
    int intensity = bin_val * hist_height / max_val;
    rectangle(hist_image, Point(i * 2, hist_height - 1), Point((i + 1) * 2 - 1, hist_height - intensity), Scalar(255, 255, 255));
}
imshow("hist", hist_image);

Mat back_img;
calcBackProject(&gray, 1, channels, hist, back_img, ranges, 1, true);

imshow("back", back_img);


waitKey(0);
return 0;

}
0 Answers
Related