OpenCV C++ API

In this section, I will introduce you some fundamental concepts of OpenCV C++ API. These concepts will help you to understand and write OpenCV C++ example programs in this tutorial more easily.


Header files


You will need to include only the opencv2/opencv.hpp header file in your program. That header file will include all the other necessary header files for your application. Therefore you don't need to bother thinking which header files should be included for your program any more.
e.g. -
#include <opencv2/opencv.hpp>


Namespace


All OpenCV classes and functions are in cv namespace. So, you have to do one of following

  • Add the using namespace cv; line just after including header files (I have used this method in all my example programs in this tutorial)
e.g. -
#include <opencv2/opencv.hpp> 
using namespace cv;
 
int main(int argc, char** argv) 
{ 
 // Read the image file 
 Mat image = imread("D:/My OpenCV Website/Eagle.jpg"); 
 return 0; 
}


  • Append the cv:: specifier at the beginning of every OpenCV classes, functions and data structures in your source code
e.g. -
#include <opencv2/opencv.hpp> 

int main(int argc, char** argv) 
{ 
 // Read the image file 
 cv::Mat image = cv::imread("D:/My OpenCV Website/Eagle.jpg"); 
 return 0; 
}


Data Types of Arrays


Data type of an array defines the number of channels, the number of bits allocated for each element and how the value of an element is represented using those bits. If an array represents an image, each elements of the array are pixels of the image.

Any single channel array should belong to one of following data types.
  • CV_8U - 8 bit unsigned integer
  • CV_8S - 8 bit signed integer
  • CV_16U - 16 bit unsigned integer
  • CV_16S - 16 bit signed integer
  • CV_32S - 32 bit signed integer
  • CV_32F - 32 bit floating point number
  • CV_64F - 64 bit float floating point number

Here I have illustrated an array of which the data type is CV_8U. It has one channel. Each element in the channel is 8 bit unsigned integers. Hence each element should have a value range from 0 to 255. A common analogy example for a single channel array is a black and white image. (Pixel value 0 represents black and 255 represents white. Pixel values in between 0 and 255 represents color in between black and white.)

Array of which the data type is CV_8U
Array of which the data type is CV_8U


We can define all of above data types for multi channel arrays. OpenCV supports up to 512 channels. Here I am going to show you how to define CV_8U data type for multi channel arrays.
  • CV_8UC1 - Single channel array with 8 bit unsigned integers which is exactly same as CV_8U
  • CV_8UC2 - 2 channel array with 8 bit unsigned integers
  • CV_8UC3 - 3 channel array with 8 bit unsigned integers
  • CV_8UC4 - 4 channel array with 8 bit unsigned integers
  • CV_8UC(n) - n channel array with 8 bit unsigned integers (n can be from 1 to 512) )

In the same way, you can derive multi channel data types using any other single-channel data types. (e.g. - CV_16SC3, CV_32FC4, CV_64FC(27), etc)


Example 1:

Here I have illustrated an array of which the data type is CV_8UC3. It has 3 channels. Each element in each channel is 8 bit unsigned integers. Hence each element should have a value range from 0 to 255. Because this is a 3 channel array, array consists of tuples with 3 elements. The first tuple is {54, 0, 34}, second tuple is {58, 78, 185} and so on. A common analogy example for a 3 channel array is a RGB image which consists of red, green and blue channels.

Array of which data type is CV_8UC3
Array of which data type is CV_8UC3


Example 2:

Here I have illustrated an array of which the data type is CV_8SC2. It has 2 channels. Each element in each channel is 8 bit signed integers. Hence each element should have a value range from -128 to 127. Because this is a 2 channel array, array consists of tuples with 2 elements. The first tuple is {-85, -127}, second tuple is {25, 23} and so on.

Array of which data type is CV_8SC2
Array of which data type is CV_8SC2


Example Usage :

  • Mat img1(3, 5, CV_32F ); //Creating a 3 x 5 single-channel array with 32 bit floating point numbers
  • Mat img2(23, 53, CV_64FC(5) ); //Creating a 23 x 53 5-channel array with 64 bit floating point numbers
  • Mat img3(Size(100, 200), CV_16UC2 ); //100 x 200 2-channel array with 16 bit unsigned integers


Note :

  1. After reading this tutorial, it should be obvious to you that the following 3 datatypes are exactly the same.
      • CV_8U
      • CV_8UC1
      • CV_8UC(1)

  2. Although CV_32FC4 is a valid data type, CV_32FC5 is not a valid data type. For arrays which consist of more than 4 channels, parentheses should be used to enclose the channel number. e.g. - CV_32FC(5).
  3. Some OpenCV functions can handle only a subset of above data types. So, read the documentation before using OpenCV functions.



Some Insight into Depth and Channels of Images


Any digital image consists of pixels. Every pixel should have some value. The minimum value for a pixel is 0 and it represents black.When the value of the pixel is increased, the intensity of that pixel is also increased. The maximum value which can be assigned for a pixel depends on the number of bits allocated for each pixels. If the number of bits allocated per pixel is 8, then the maximum value of that pixel is 255 (11111111 in binary)

Now what is depth of an image? The image depth means the number of bits allocated for each pixel. If it is 8, each pixel can have a value between 0 and 255. If it is 4, each pixel can have a value between 0 to 15 (1111 in binary).


Gray-scale Image


Here is a simple model of an image with a depth of 8 bits. Each small box represents a pixel. So, each box may contain a value between 0 to 255.

Gray-scale Image with a depth of 8
Gray-scale Image with a depth of 8



Here is some important properties of the above image.
  • Image depth is 8 bits.
  • Image consists of single channel.
  • The height of the image is 4 pixel.
  • The width of the image is 5 pixels.
  • The resolution of this image is 5 x 4.

This is a gray-scale image (black and white image) because it only consists of a single channel. Therefore this image does not contain any color information. If the value of this pixel is higher, it will be shown more brighter. If the value is low, it will be shown more darker.


Color Image


Following image is a simple model of a color image. Color image should consist of at least 3 planes; Red, Green and Blue. Any pixel is a combination of the three values. Any color can be created by combining these 3 basic colors.

Examples -
  • (255, 0, 0) represent pure red. 
  • (0, 255, 0) represent pure green. 
  • (0, 0, 255) represents pure blue. 
  • (255, 0, 255) represents pure violate. 

R, G, B planes of a color image
R, G, B planes of a color image

In the above image, top left pixel is (23, 231, 46). It will be shown as a greenish color because the green value (231) of that pixel is significantly larger than the red (23) and blue (46) value.

Here is some important properties of the above image.
  • Image depth is 24 bits. (because each pixel is represented with 8 x 3 bits (8 bits from each channel)
  • The image consists of 3 channels.
  • The height of the image is 4 pixel. 
  • The width of the image is 5 pixels.
  • The resolution of this image is 5 x 4.

Note -
OpenCV library functions usually read images in BGR format which means blue plane first, green color plane next and the red plane at the end which is exactly the reverse order of the above image.



Next Lesson : Load & Display Image



58 comments:

  1. Replies
    1. Great Article Image Processing Projects Deep Learning Projects for Final Year JavaScript Training in Chennai JavaScript Training in Chennai The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. nyc explanation, understood clearly

    ReplyDelete
  3. In example 1, where you have illustrated an array of which the data type is CV_8UC3 with 3 channels. In 3rd row 4th column of the array at the top the value is 278. Is it normal? (Asking out of curiosity cause I'm a beginner)

    ReplyDelete
  4. This is really helpful for beginners. Thanks for sharing.

    ReplyDelete
  5. Helpful resource. thanks

    ReplyDelete
  6. This is the code

    #include

    using namespace cv;

    int main(int argc, char** argv)
    {
    //Read the image from file
    Mat image = imread("C:\OpenCv pics\download.jpg");
    return 0;

    }

    i run it in visual studio 2019 release x64 but the code runs and it will not open any image.

    ReplyDelete
    Replies
    1. Probably, you gave wrong path. You should check it with if condition. In addition, You should try these //, \\, / instead of \(back slash) in your code. Maybe it works.

      Delete
  7. C++ was always easy for me to understand. Although, when I was studying in the university, many of my peers had difficulties with it.

    ReplyDelete
  8. Great and useful.
    Thanks

    ReplyDelete
  9. This is very helpfull , thank's for sharing

    ReplyDelete
  10. This is my first visit to your blog! We are a team of volunteers and new
    initiatives in the same niche. Blog gave us useful information to work. You
    have done an amazing job!

    artificial intelligence training in Bangalore

    ReplyDelete
  11. In short, this is the description of the relation between data science and machine learning. Hopefully, now you have a much better understanding of the two fields. best course to learn artificial intelligence

    ReplyDelete
  12. Great instruction! If you make video for youtube, you can visit our site https://soclikes.com/ to get youtube views

    ReplyDelete
  13. This is a wonderful article, Given so much info in it, Thanks for sharing. CodeGnan offers courses in new technologies and makes sure students understand the flow of work from each and every perspective in a Real-Time environment react course in vijayawada. ,

    ReplyDelete
  14. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!
    Data Science Training in Hyderabad

    ReplyDelete
  15. This is a great motivational article. In fact, I am happy with your good work. They publish very supportive data, really. Continue. Continue blogging. Hope you explore your next post
    data science course

    ReplyDelete
  16. This post is very simple to read and appreciate without leaving any details out. Great work!
    business analytics courses in aurangabad

    ReplyDelete
  17. Hello, I do think this is an incredible site. I stumbledupon it ;) I will return to once since I have saved as a most loved it. Cash and opportunity is the most ideal approach to change, may you be rich and keep on helping other people.
    Chancellor Portal

    ReplyDelete
  18. Great day! I might have sworn I've visited this site before however in the wake of perusing a considerable lot of the posts I understood it's unfamiliar to me. In any case, I'm unquestionably cheerful I found it and I'll be bookmarking it and returning frequently!
    earthcycle

    ReplyDelete
  19. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    data science course in noida

    ReplyDelete
  20. Stickers2GO is the fastest and easiest way to turn any artwork, logo, or image into beautiful custom stickers. Order in seconds and get free online proofs, free shipping and super quick turnaround chk this website custom stickers printing

    ReplyDelete
  21. Really Nice Information It's Very Helpful All courses Checkout Here.
    best data science course

    ReplyDelete
  22. Your content is very unique and understandable useful for the readers keep update more article like this.
    best data science courses

    ReplyDelete
  23. Thanks for posting the best information and the blog is very informative.Data science course in Faridabad

    ReplyDelete

  24. I think I have never seen such blogs before that have completed things with all the details which I want. So kindly update this ever for us.

    Best Institutes For Digital Marketing in Hyderabad

    ReplyDelete
  25. I must appreciate you for providing such valuable content for us. To make our dreams a reality, everyone has to put up a hard struggle in their life. Here I am making my small effort to arrange up the list of highest paying Jobs in India. We provide one of the best courses for you.
    1) Data Science course in Delhi
    2) Artificial Intelligence Course in Delhi
    3) Machine Learning course in Delhi
    4) Business Analytics courses in Delhi
    5) Digital marketing course in Delhi
    6) Full Stack Software Developer course in Delhi.

    ReplyDelete
  26. bespoke packaging boxes At Bespoke Packaging UK we strongly believe in the interests of bespoke packaging, which has multiple benefits.

    ReplyDelete
  27. Thanks for posting the best information and the blog is very helpful.artificial intelligence course in hyderabad

    ReplyDelete
  28. Thanks for posting the best information and the blog is very helpful.artificial intelligence course in hyderabad

    ReplyDelete
  29. Best Software Training Institute in Delhi Madrid Software offers strategic training paths for the certification skills required to support today's technologies, while offering a Business Analytic course, Data science courses in Delhi, Career in AI and Digital Marketing Course in Delhi for clients looking to implement new/upgraded business applications.

    ReplyDelete
  30. The web site loading speed is incredible. It seems that you’re doing any distinctive trick. In addition, The contents are masterpiece. you have done a great activity on this matter!custom cosmetic boxes | custom cosmetic boxes

    ReplyDelete
  31. Thanks for posting the best information and the blog is very helpful.digital marketing institute in hyderabad

    ReplyDelete
  32. Really awesome blog!!! I finally found great post here.I really enjoyed reading this article. Thanks for sharing your innovative ideas to our vision. your writing style is simply awesome with useful information. Very informative, Excellent work! I will get back here. . AWS Course in Chennai

    ReplyDelete
  33. Brij Namkeen is the best Food Manufacturers Company in India since Eight Decades. Buy Brij sweets online, Buy Namkeen Online, Snacks and Brij Namkeen Special Orange Burfee Online.

    ReplyDelete
  34. Brij Namkeen is the best Food Manufacturers Company in India since Eight Decades. Buy Brij sweets online, Buy Namkeen Online, Snacks and Brij Namkeen Special Orange Burfee Online.

    ReplyDelete
  35. https://iibminternships.com/

    IIBM Internships | Online Certification Courses for Working Professionals

    IIBM Internships provides certification courses for working professionals in the field of Data Science, Full Stack, Six Sigma, Cloud Computing and various other courses...

    ReplyDelete
  36. Download Cricket Mazza 11 for Android Live Line & Fastest IPL Score. Get Live Cricket Scores, Scorecard, Commentary, Match Info and Schedules of All International & Domestic Matches, Series wise Stats, Records, Analysis and Facts, Trending News and Tweets, Recent ICC Player and Team Rankings. Also Download best cricket game apps for ios, including Beach Cricket, Cricket T20 Fever 3D, Real Cricket 17 and other top answers suggested and ranked.

    ReplyDelete
  37. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work


    Best Data Science courses in Hyderabad

    ReplyDelete
  38. Amazing great post it is very informative keep up the good work.
    plain Jewelry box

    ReplyDelete