Opencv create new image using cv::Mat

c++, image-processing, opencv

Solution

First, you need the following information to create the image:

- Width: 301 pixels

- Height: 260 pixels

- Each pixel value (intensity) is 0 ~ 255: an 8-bit unsigned integer

- Supports all RGB colors: 3 channels

- Initial color: black = (B, G, R) = (0, 0, 0)

You can create the Image using `cv::Mat`:

Mat grHistogram(260, 301, CV_8UC3, Scalar(0, 0, 0));

The `8U` means the 8-bit Usigned integer, `C3` means 3 Channels for RGB color, and `Scalar(0, 0, 0)` is the initial value for each pixel. Similarly,

line(grHistrogram,pt1,pt2,Scalar(255,255,255),1,8,0);

is to draw a line on `grHistogram` from point `pt1` to point `pt2`. The color of line is white (255, 255, 255) with 1-pixel thickness, 8-connected line, and 0-shift.

Sometimes you don't need a RGB-color image, but a simple grayscale image. That is, use one channel instead of three. The type can be changed to `CV_8UC1` and you only need to specify the intensity for one channel, `Scalar(0)` for example.

Back to your problem,

Why this happening since, both create a Mat image structure?

Because you need to specify the type of the `Mat`. Is it a color image `CV_8UC3` or a grayscale image `CV_8UC1`? They are different. Your program may not work as you think if you use `Scalar(255)` on a `CV_8UC3` image.

What is the purpose of const cv:Scalar &_s ?

`cv::Scalar` is use to specify the intensity value for each pixel. For example, `Scalar(255, 0, 0)` is blue and `Scalar(0, 0, 0)` is black if type is `CV_8UC3`. Or `Scalar(0)` is black if it's a `CV_8UC1` grayscale image. Avoid mixing them together.

Problem

I'm new to OpenCV and I'm trying on some sample codes. In one code, ``` Mat gr(row1, col1, CV_8UC1, scalar(0)); int x = gr.at<uchar> (row, col); ``` And in another one, ``` Mat grHistrogram(301, 260, CV_8UC1, Scalar(0,0,0)); line(grHistrogram, pt1, pt2, Scalar(255,255,255), 1, 8, 0); ``` Now my question is if I used `scalar(0)` instead of `scalar(0,0,0)` in second code, The code doesn't work. My question is - Why this happening since both create a Mat image structure. - What is the purpose of const `cv:Scalar &_s`. I search the documentaion from OpenCV site (opencv.pdf, opencv2refman.pdf) and Oreilly's OpenCV book. But couldn't find an explained answer. I think I'm using the `Mat(int _rows, int _cols, int _type, const cv:Scalar &_s)` struct.

Original source