Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of each column opencv

Tags:

opencv

In Matlab, If A is a matrix, sum(A) treats the columns of A as vectors, returning a row vector of the sums of each column.

sum(Image); How could it be done with OpenCV?

like image 828
space Avatar asked Feb 23 '11 21:02

space


People also ask

How do you find the sum of a column in a matrix in python?

Use the numpy. sum() Function to Find the Sum of Columns of a Matrix in Python. The sum() function calculates the sum of all elements in an array over the specified axis. If we specify the axis as 0, then it calculates the sum over columns in a matrix.


2 Answers

Using cvReduce has worked for me. For example, if you need to store the column-wise sum of a matrix as a row matrix you could do this:

CvMat * MyMat = cvCreateMat(height, width, CV_64FC1);
// Fill in MyMat with some data...

CvMat * ColSum = cvCreateMat(1, MyMat->width, CV_64FC1);
cvReduce(MyMat, ColSum, 0, CV_REDUCE_SUM);

More information is available in the OpenCV documentation.

like image 115
Srinath Sridhar Avatar answered Oct 09 '22 03:10

Srinath Sridhar


EDIT after 3 years:

The proper function for this is cv::reduce.

Reduces a matrix to a vector.

The function reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of a raster image. In case of REDUCE_MAX and REDUCE_MIN , the output image should have the same type as the source one. In case of REDUCE_SUM and REDUCE_AVG , the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes.

OLD: I've used ROI method: move ROI of height of the image and width 1 from left to right and calculate means.

 Mat src = imread(filename, 0);     
 vector<int> graph( src.cols );
 for (int c=0; c<src.cols-1; c++)
 {
     Mat roi = src( Rect( c,0,1,src.rows ) );
     graph[c] = int(mean(roi)[0]);
 }

 Mat mgraph(  260, src.cols+10, CV_8UC3); 
 for (int c=0; c<src.cols-1; c++)
 {
     line( mgraph, Point(c+5,0), Point(c+5,graph[c]), Scalar(255,0,0), 1, CV_AA);    
 }

 imshow("mgraph", mgraph);
 imshow("source", src);

BLOT-stripeIntensity graph

EDIT: Just out of curiosity, I've tried resize to height 1 and the result was almost the same:

 Mat test;
 cv::resize(src,test,Size( src.cols,1 ));
 Mat mgraph1(  260, src.cols+10, CV_8UC3); 
 for(int c=0; c<test.cols; c++) 
 {
        graph[c] = test.at<uchar>(0,c);
 }
 for (int c=0; c<src.cols-1; c++)
 {
     line( mgraph1, Point(c+5,0), Point(c+5,graph[c]), Scalar(255,255,0), 1, CV_AA);     
 }
 imshow("mgraph1", mgraph1);

Cols mean graph by resizing to height 1

like image 33
Valentin H Avatar answered Oct 09 '22 03:10

Valentin H