OpenCV scalar datatype, when to use?

Jürgen K. picture Jürgen K. · Oct 1, 2015 · Viewed 9.8k times · Source

Here we can hava a look on OpenCV's basic structures. My question is what exactly the datatype "scalar" is and when do i use it.

Here you can see its definition:

template<typename _Tp> class CV_EXPORTS Scalar_ : public Vec<_Tp, 4>
{
public:
//! various constructors
Scalar_();
Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);
Scalar_(const CvScalar& s);
Scalar_(_Tp v0);

//! returns a scalar with all elements set to v0
static Scalar_<_Tp> all(_Tp v0);
//! conversion to the old-style CvScalar
operator CvScalar() const;

//! conversion to another data type
template<typename T2> operator Scalar_<T2>() const;

//! per-element product
Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const;

// returns (v0, -v1, -v2, -v3)
Scalar_<_Tp> conj() const;

// returns true iff v1 == v2 == v3 == 0
bool isReal() const;
};

typedef Scalar_<double> Scalar;

Here you can see an example how they use it

// make a 7x7 complex matrix filled with 1+3j.
Mat M(7,7,CV_32FC2,Scalar(1,3));
// and now turn M to a 100x60 15-channel 8-bit matrix.
// The old content will be deallocated
M.create(100,60,CV_8UC(15));

So my question is why can't i use double in this case? Or arrays?

Thanks in advance

Answer

Miki picture Miki · Oct 1, 2015

A Scalar is a

Template class for a 4-element vector derived from Vec.

Being derived from Vec<Tp, 4> , Scalar and Scalar can be used just as typical 4-element vectors. The type Scalar is widely used in OpenCV to pass pixel values.

You can initialize a Mat also differently, like:

Mat img(10, 10, CV_32FC2, { 2, 3 });

that will be internally converted to a Vec_. But since the signature of the Matconstructor accepts a Scalar, you better use a Scalar.

This will allow to use always the Scalar to pass pixel values for all images with 1 to 4 channels.