对于一幅灰度图像,积分图像中的任意一点(x,y)的值是指从图像的左上角到这个点的所构成的矩形区域内所有的点的灰度值之和:
I表示积分图像,G表示原始图像。则 I(x,y)=sum(G(i,j)),其中 0<=i<=x,0<=j<=y.
在实际的计算过程中,对于一个点(x,y)的值等于:
I(x,y)=I(x-1,y)+I(x,y-1)-I(x-1,y-1)+G(i,j) (I:该点的积分图像值,G:该点的灰度值)
在实际的编程实现过程中可以对有图像的大小进行扩展,左边扩展一列,顶端扩展一行, 即:I(-1,j)=0,I(i,-1)=0;
快速算法:
s(x,y) = s(x,y-1) + i(x,y);
ii(x,y) = ii(x-1,y) + s(x,y)
其中s(x,y)是列的积分值,i(x,y)是原始图像的灰度值,ii(x,y)是积分图的最终值。
#include<opencv2\core\core.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main(int argc,char* argv[])
{
//读取图像
Mat image;
image=imread("lena.bmp",IMREAD_COLOR);
if(image.empty())
{
cerr<<"Failure in loading image"<<endl;
return -1;
}
//转换成灰度图像
Mat grayImage;
cvtColor(image,grayImage,COLOR_BGR2GRAY);
//定义、计算积分图像,积分图像比灰度图像多一行一列
Mat integralImage=Mat::zeros(grayImage.rows+1,grayImage.cols+1,CV_32SC1);
for(int i=0;i<grayImage.rows;i++)
{
for(int j=0;j<grayImage.cols;j++)
{
integralImage.at<int>(i+1,j+1)=integralImage.at<int>(i,j+1)
+integralImage.at<int>(i+1,j)
-integralImage.at<int>(i,j)
+grayImage.at<unsigned char>(i,j);
}
}
//真正的积分图像
Mat realIntegralImage=integralImage(Range(1,integralImage.rows),Range(1,integralImage.cols));
/*cout<<realIntegralImage.row(0)<<endl;*/
//Opencv中自带的积分图像计算
Mat integralImage_integral;
integral(grayImage,integralImage_integral);
//下面两行代码用来对比自己的积分图像和Opencv自己计算的积分图像是否一样
//cout<<integralImage.row(1)<<endl;
//cout<<integralImage_integral.row(1)<<endl;
imshow("src",image);
imshow("gray",grayImage);
waitKey(0);
return 0;
}