灰度直方图计算 直方图相似性度量 图像分块

//图像分块

cv::Mat img_region[REGION_W*REGION_H];
int region_w = cvRound(img.cols / REGION_W);
int region_h = cvRound(img.rows / REGION_H);
int index = 0;
for (int i = 0; i < REGION_W;i++)
{
for (int j = 0; j < REGION_H; j++)
{
cv::Rect region_rect;
region_rect.x = i * region_w;
   region_rect.y = j * region_h;
region_rect.width = ((region_rect.x + region_w) < img.cols? region_w : (img.cols - region_rect.x));
region_rect.height = ((region_rect.y + region_h) < img.rows? region_h : (img.rows - region_rect.y));
img_region[index] = cv::Mat(img, region_rect);
cv::Mat ddd = img_region[index];
index++;
}

}

// 计算每块的直方图,然后连成一个向量

cv::Mat histTemp;
//256个,范围是0,255. 
const int histSize = HISTSIZE;  
float range[] = {0, 255};  
const float *ranges[] = {range};  
const int channels = 0;  
cv::Mat histogram(REGION_W*REGION_H * histSize , 1, CV_32FC1);
int hist_w = 256; int hist_h = HIST_HEIGHT;
int bin_w = cvRound( (double) hist_w/histSize);
for (int i = 0; i < REGION_W*REGION_H; i++)
{
cv::calcHist(&img_region[i], 1, &channels, cv::Mat(), histTemp, 1, &histSize, &ranges[0], true, false);
/// Normalize the result to [ 0, histImage.rows ]
cv::normalize(histTemp, histTemp, 0, hist_h, NORM_MINMAX, -1, Mat() );
for (int j = 0; j < histSize; j++)
{
histogram.at((i * histSize + j),0) = histTemp.at(j,0);
}
}
// 直方图显示
cv::Mat histImage( hist_h, hist_w *REGION_W*REGION_H , CV_8UC3, Scalar( 0,0,0) );
for( int i = 1; i < histSize * REGION_W*REGION_H; i++ )
{
cv::line( histImage, Point( bin_w*(i-1), hist_h - cvRound(histogram.at(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(histogram.at(i)) ),
Scalar( 255, 0, 0), 2, 8, 0  );

}

// 直方图比对

cv::compareHist(hist1,hist2,0);

注意:参考直方图比对的公式,应该对每块直方图分别比对,最后算乘积;不要对连起来的一维向量进行匹配。

灰度直方图计算 直方图相似性度量 图像分块_第1张图片


你可能感兴趣的:(图像处理)