1. 程式人生 > >opencv學習---計算影象的水平積分投影和垂直積分投影

opencv學習---計算影象的水平積分投影和垂直積分投影

#include<opencv2\opencv.hpp>
#include<stdio.h>
using namespace cv;
Mat VerticalProjection(Mat srcImage)//垂直積分投影
{
	if (srcImage.channels() > 1)
		cvtColor(srcImage, srcImage, CV_RGB2GRAY);
	Mat srcImageBin;
	threshold(srcImage, srcImageBin, 120, 255, CV_THRESH_BINARY_INV);
	imshow("二值圖", srcImageBin);
	int *colswidth = new int[srcImage.cols];  //申請src.image.cols個int型的記憶體空間
	memset(colswidth, 0, srcImage.cols * 4);  //陣列必須賦初值為零,否則出錯。無法遍歷陣列。
	//  memset(colheight,0,src->width*4);  
	// CvScalar value; 
	int value;
	for (int i = 0; i < srcImage.cols; i++)
	for (int j = 0; j < srcImage.rows; j++)
	{
		//value=cvGet2D(src,j,i);
		value = srcImageBin.at<uchar>(j, i);
		if (value == 255)
		{
			colswidth[i]++; //統計每列的白色畫素點  
		}
	}
	Mat histogramImage(srcImage.rows, srcImage.cols, CV_8UC1);
	for (int i = 0; i < srcImage.rows; i++)
	for (int j = 0; j < srcImage.cols; j++)
	{
		value = 255;  //背景設定為白色。 
		histogramImage.at<uchar>(i, j) = value;
	}
	for (int i = 0; i < srcImage.cols; i++)
	for (int j = 0; j < colswidth[i]; j++)
	{
		value = 0;  //直方圖設定為黑色
		histogramImage.at<uchar>(srcImage.rows - 1 - j, i) = value;
	}
	imshow(" 垂直積分投影圖", histogramImage);
	return histogramImage;
}
Mat HorizonProjection(Mat srcImage)//水平積分投影
{
	if (srcImage.channels() > 1)
		cvtColor(srcImage, srcImage, CV_RGB2GRAY);
	Mat srcImageBin;
	threshold(srcImage, srcImageBin, 120, 255, CV_THRESH_BINARY_INV);
	imshow("二值圖", srcImageBin);
	int *rowswidth = new int[srcImage.rows];  //申請src.image.rows個int型的記憶體空間
	memset(rowswidth, 0, srcImage.rows * 4);  //陣列必須賦初值為零,否則出錯。無法遍歷陣列。
	int value;
	for (int i = 0; i<srcImage.rows; i++)
	for (int j = 0; j<srcImage.cols; j++)
	{
		//value=cvGet2D(src,j,i);
		value = srcImageBin.at<uchar>(i, j);
		if (value == 255)
		{
			rowswidth[i]++; //統計每行的白色畫素點  
		}
	}
	Mat histogramImage(srcImage.rows, srcImage.cols, CV_8UC1);
	for (int i = 0; i<srcImage.rows; i++)
	for (int j = 0; j<srcImage.cols; j++)
	{
		value = 255;  //背景設定為白色。 
		histogramImage.at<uchar>(i, j) = value;
	}
	//imshow("d", histogramImage);
	for (int i = 0; i<srcImage.rows; i++)
	for (int j = 0; j<rowswidth[i]; j++)
	{
		value = 0;  //直方圖設定為黑色
		histogramImage.at<uchar>(i, j) = value;
	}
	imshow("水平積分投影圖", histogramImage);
	delete[] rowswidth;//釋放前面申請的空間
	return histogramImage;

}
int main()
{
	Mat srcImage = imread("145.png");
	imshow("原圖", srcImage);
	Mat VP;
	VP = VerticalProjection(srcImage);
	Mat HP;
	HP = HorizonProjection(srcImage);
	waitKey(0);
	return 0;

}

執行結果: