積分圖的實現

積分圖的實現


//改進的計算像素灰度值積分圖像
//image_Src:灰度圖
//image_Integral:image_Src大小相同的CV_32SC1類型
//方法:Integral(y,x) = Integral(y-1,x) + rowSum(y);
void CalculateIntegralImage(const Mat &image_Src,Mat &image_Integral)
{
	////////////step 1.重新分配圖像(如果需要)/////////////////
	//新圖像的大小
	int width_Dst=image_Src.cols;
	int height_Dst=image_Src.rows;
	image_Integral.create(Size(width_Dst,height_Dst),CV_32SC1);//如果重新分配,之前的空間會扔掉
	image_Integral.setTo(Scalar(0));

	////////step 2.計算積分圖////////////////////////
	//參數
	int widthStep_Src=image_Src.step1(0);//行的通道數,這裏一定要注意!!!
	int widthStep_Integral=image_Integral.step1(0);//行的通道數
	
	int channelCount_Src=image_Src.step1(1);//每個點的通道數
	int channelCount_Integral=image_Integral.step1(1);//每個點的通道數

	//第一行
	uchar *row_Src=image_Src.data;
	int *row_Integral=(int *)image_Integral.data;//注意指針的轉換
	for (int y=0;y<=image_Src.rows-1;++y)
	{
		int sum=0;//當前行的累加和
		//列
		uchar *col_Src=row_Src;
		int *col_Integral=row_Integral;
		for (int x=0;x<=image_Src.cols-1;++x)
		{
			//該行的累加
			sum+=col_Src[0];

			//計算第0行,第一行單獨處理
			if (y==0)
			{
				col_Integral[0]=sum;
			}
			else
			{
				//非第0行
				//當前行累加和+同列的上一個元素的值
				col_Integral[0]=sum+col_Integral[0-widthStep_Integral];//下標
				//col_Integral[0]=sum+*(col_Integral-image_Integral.cols);//指針移動

			}

			//下一個像素
			col_Src++;
			col_Integral++;

		}
		//下一行
		row_Src+=widthStep_Src;
		row_Integral+=widthStep_Integral;
	}


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章