# Normalize vector

Hello

I have column vectors stored in a matrix M. How do i normalize each vector ? I have tried

normalize(M.col(i), M.col(i)); reduce(M, sum, 0, CV_REDUCE_SUM, CV_32FC1);

But the results do not give me a 1 for every column. Help thanks

edit retag close merge delete

Sort by ยป oldest newest most voted

Try multiply(M.col(i), 1.0/(sum(M.col(i))(0)), M.col(i));

This takes the column, finds the sum, and multiplies the column by 1/sum. Then use the reduce to check.

If you want to use the normalize function, you need to change the norm type to NORM_L1, and it will do the same thing. Actually, just do this, that's better. Here's the documentation on the normalize function so you can see why NORM_L2 wasn't working and why NORM_L1 will.

more

Hello thanks ! I did not know such a function existed. What is the use of (0) in sum(M.col(i))(0) ? I looked at http://docs.opencv.org/2.4/modules/co... but it only specifies the input..

( 2016-03-22 07:34:41 -0500 )edit

The sum() function returns a cv::Scalar, which is four doubles together. The first contains the sum of the first channel, the second, channel 2, ect. Since you have one channel, you want the first double, which is index 0.

But you should use normalize with NORM_L1, that's more clear, and possibly a bit faster.

( 2016-03-22 15:48:19 -0500 )edit

Official site

GitHub

Wiki

Documentation