7

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

Jürgen K.
  • 3,427
  • 9
  • 30
  • 66
  • 4
    `Scalar` is just for ease of use. As most of OpenCV operates on maximum 4 channel images, so `Scalar` is a simple class which is actually a `cv::Vec` of length 4, which can be used by OpenCV algorithms according to number of channels of the image. Instead of creating an array of different length each time, you just pass a scalar value to the algorithm. – sgarizvi Oct 01 '15 at 11:36
  • Thanks for a fast response – Jürgen K. Oct 01 '15 at 12:51
  • Does `scalar()` return a value – Giorgi Gvimradze May 02 '19 at 15:47

1 Answers1

6

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.

Community
  • 1
  • 1
Miki
  • 40,887
  • 13
  • 123
  • 202