Opencv multiply scalar and matrix
Asked Answered
C

5

19

I have been trying to achieve something which should pretty trivial and is trivial in Matlab.

Using methods of OpenCV, I want to simply achieve something such as:

cv::Mat sample = [4 5 6; 4 2 5; 1 4 2];      
sample = 5*sample;

After which sample should just be:

[20 25 30; 20 10 25; 5 20 10]

I have tried scaleAdd, Mul, Multiply and neither allow a scalar multiplier and require a matrix of the same "size and type". In this scenario I could create a Matrix of Ones and then use the scale parameter but that seems so very extraneous

Any direct simple method would be great!

Congreve answered 27/7, 2013 at 0:3 Comment(2)
Shouldn't 24 be 25 instead??? :PEqualizer
What language is the code in?Epicritic
C
24

OpenCV does in fact support multiplication by a scalar value with overloaded operator*. You might need to initialize the matrix correctly, though.

float data[] = {1 ,2, 3,
                4, 5, 6,
                7, 8, 9};
cv::Mat m(3, 3, CV_32FC1, data);
m = 3*m;  // This works just fine

If you are mainly interested in mathematical operations, cv::Matx is a little easier to work with:

cv::Matx33f mx(1,2,3,
               4,5,6,
               7,8,9);
mx *= 4;  // This works too
Claman answered 27/7, 2013 at 4:4 Comment(2)
This function only works for single channeled images. This therefore does not work generally. You would have to split all the channels first and then recombine then, eg //(3) Split the RGB image vector<Mat> imgPlanes(3); split(matImage, imgPlanes); Mat matImageK = imgPlanes[0];Sheronsherourd
is there no / operator?Annam
P
5

For java there is no operator overloading, but the Mat object provides the functionality with a convertTo method.

Mat dst= new Mat(src.rows(),src.cols(),src.type());
src.convertTo(dst,-1,scale,offset);

Doc on this method is here

Passant answered 16/12, 2017 at 21:5 Comment(0)
S
3

For big Mats you should use forEach.

If C++11 is available:

m.forEach<double>([&](double& element, const int position[]) -> void
{
element *= 5;
}
);
Shelbashelbi answered 24/9, 2018 at 8:31 Comment(1)
why should this be better than using the builtin matrix-scalar multiplication or cv::multiply?Anesthesiologist
K
1

something like this.

Mat m = (Mat_<float>(3, 3)<<
                    1, 2, 3,
                    4, 5, 6,
                    7, 8, 9)*5;
Kingcup answered 27/7, 2013 at 8:45 Comment(0)
M
1
Mat A = //data;//source Matrix
Mat B;//destination Matrix
Scalar alpha = new Scalar(5)//factor
Core.multiply(A,alpha,b);
Mayfield answered 3/6, 2017 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.