Opencv2 + entry series (2): Opening, creating, and displaying images (command line)

Source: Internet
Author: User
Tags scalar
Pre-Knowledge: A brief knowledge of digital images

Here is only the most basic knowledge. If you have listened to a lesson, you can skip it.

Color Image:

For a digital image, for a color digital image in an RGB color space, it has a total of X-height pixel grids, the color of each grid is synthesized by three primary colors: blue, green, and red. It's easy. The synthesis of the primary colors has been learned. In the computer, values B, G, and r can be selected from 0 to 255. Different values can be combined to produce different colors, generally, a total of 255*255*255 colors can be formed.

Grayscale image:

If all pixels in the image are represented by the brightness from black to white (0 to 255), the image will be a gray image (imagine a black or white image ).

Binary Image:

In a grayscale image, set the brightness of all pixels whose brightness is greater than a certain value (binarization threshold) to 255, and set the remaining values to 0. Then the binary image is obtained, it will only be black and white images, similar to black and white wood.

 

1. Opening an image

If you have made some achievements in C ++ programming and have a general understanding of classes, objects, and namespaces, you must first add the corresponding header files to use opencv functions. We add core. HPP and highgui. HPP and reference the CV namespace.

1.1 open an existing image

In opencv 2 + versions, the image storage type is mat. The function for loading the image is imread, and the function for displaying the image is imshow. It's easy, you only need a few functions to write an image browser ~).

Because it is too simple, put the Code directly:

# Include "stdafx. H "# include <opencv2/CORE/core. HPP> # include <opencv2/highgui. HPP> using namespace CV; int main () {mat image = CV: imread ("img.jpg"); // read img.jpg to image, you can write relative paths or absolute paths namedwindow ("Image 1"). // define a window named "Image 1" imshow ("Image 1", image ); // display the image waitkey () in "Image 1"; // wait for the key to return 1 ;}

Every sentence is annotated, which is easy to understand, isn't it. Because the namespace of CV is referenced in advance, you do not need to add "CV:" Before each sentence. Otherwise, you will see the following code:

# Include "stdafx. H "# include <opencv2/CORE/core. HPP> # include <opencv2/highgui. HPP> int main () {CV: mat image = CV: imread ("img.jpg"); // read img.jpg to image, here you can write relative paths or absolute paths CV: namedwindow ("Image 1"); // define a window CV named "Image 1 :: imshow ("Image 1", image); // display image CV: waitkey () in "Image 1" in the window; // wait for the key to return 1 ;}

In short, the final effect should be as follows:

Brief description:

1. The Mat type is the data structure used in opencv2 to save image or matrix information. You can use the above method to directly read an image during initialization, or specify the initial size and color. Let's talk about it later.

2. Using the imread function, we can load an image from the specified path to the memory (stored as a mat variable ). Its function prototype is:

It is known that it has a default parameter flags = 1, which indicates that the image opened by the program is a three-channel (BGR three-channel) by default, which is a color image, if you set flags to 0 when calling the function, the image will be loaded into a grayscale image (single channel ). When it is set to-1, 2, 4, there is another significance, but more detailed function description you are going to go left to see the opencv official manual, after all, this article is not a document translation, right.

Of course, sometimes you cannot determine whether the image you specified can be opened smoothly (the image does not exist, the image is damaged, etc.). Therefore, when using the opened image, it is best to judge whether the image is correctly read, just like this.

Mat image = imread ("img.jpg", cv_load_image_color); // read img.jpg to the image. You can write relative paths or absolute paths if (! Image. Data) {// do something image not read successfully}

3. before using the imshow function to display images, remember to use namedwindow to define a window. You can set the window parameters, such as size, position, and scaling. For details, see the official documentation.

1.2 create an image in memory

OK, of course, in addition to reading images from files, we can also directly create an image in the computer memory. We do this. When defining a mat variable, there are 24 kinds of overloading that can be used to specify the initial value of the variable.

// You can write: mat image2 (319,480, cv_8uc3, scalar (, 0); // write: mat image3 (image. size (), cv_8uc3, scalar (0,255, 0); // or write as follows: mat image4 (image );

The first method is to create an 8-bit 3-channel color image with a width of 480 and a height of 319. The color is 255 blue. In the code, cv_8uc3 is a macro definition that represents 8-bit and 3-channel color images. Similar macro definition also includes cv_8u, which represents eight-bit gray images. Scalar (, 0) represents the color of the created image, and three numbers represent the BGR channel.

The second method is to create a green image of the same size as the image.

Chapter 3 writing rules indicates that an image is directly copied to the memory space of image4.

 

Ii. Storage Format of Mat objects (simple)

This section is very important. Only by understanding the mat variable can you operate images well!

This section is very important. Only by understanding the mat variable can you operate images well!

Because it is very important, I will say it twice, but if I want to talk about mat in detail, it is estimated that the entire article is not enough, so I can only give a brief description here.

The mat class is used to save the data structure of the image. Its default size is 0. The method for loading the image data has been mentioned in the article. If you forget it, go back and review it. After the mat object leaves the scope, the memory allocated by it will be automatically released, and the cvrelease image will not be used as before. The following is a simple structure of the mat class:

Mat {public ://... ... Many methods ....../*! Including several fields:-magic signature-continuity mark-depth (Note: Should be a bit deep)-number of channels */INT flags; (Note: I do not know how to use flags )//! The dimension of the array,> = 2int dims ;//! The number of rows and columns or (-1,-1). At this time, the array has exceeded two-dimensional int rows, cols ;//! Pointer to data: uchar * data ;//! Pointer Reference Counter; // when the array points to the data allocated by the user, when the pointer is nullint * refcount; // other members ...};

Mat. step defines the data layout, which represents the Data Length occupied by pixels in a row of the image. Mat. data points to the beginning of the array data, and mat. elemsize () returns the length of the array element. Therefore, the data in column M of row N can be obtained in this way, and the formula is not difficult to understand.

Data = mat. Data + (n-1) × mat. Step + (m-1) × mat. elemsize ();

Mat. channels () indicates the number of channels of the image. If it is a grayscale image, there is nothing to say about data storage. The first line is arranged one by one in pixels, followed by the second and third rows. If there are three channels, the B-channel value of the first pixel is saved first, then the G-channel value, and finally the R-channel value. Then store the second pixel and the third pixel ......

Well, it seems that this is enough. You can use and learn the remaining Usage After advanced learning. If you have any omissions, edit the blog. It's time to finish. I found this article is too long ......

 

Opencv2 + entry series (2): Opening, creating, and displaying images (command line)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.