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



104 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
  39. This website and I conceive this internet site is really informative ! Keep on putting up!
    data scientist course

    ReplyDelete
  40. Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info.
    Pie Boxes USA
    buy packaging Boxes

    ReplyDelete
  41. You totally coordinate our desire and the assortment of our data.
    ai course

    ReplyDelete
  42. Virtualmindinfotech is a Full-Stack Digital Transformation Company. We provide Digital Marketing Service, Website Design service, Web Development Services that will increase your website traffic, conversion rate and overall revenue. Contact us for more info.

    ReplyDelete
  43. You've made some valid statements there. I looked on the web for extra data about the issue and discovered a great many people will oblige your perspectives on this site. best interiors

    ReplyDelete

  44. Nice post. I used to be checking constantly this blog and I am impressed! Extremely useful info particularly the ultimate section 🙂 I take care of such information a lot. I was seeking this certain information for a long time. Thank you and best of luck.
    Report writing on blood donation camp

    ReplyDelete
  45. Amazing web journal much obliged for sharing the important information.it gets to be simple to study and effectively understand the information. The useful article was exceptionally supportive. too curiously and contains great data. Composable storage

    ReplyDelete
  46. I'm cheerful I found this blog! Every now and then, understudies need to psychologically the keys of beneficial artistic articles forming...

    Data Science Training in Hyderabad

    ReplyDelete
  47. Great work. Really nice blog. Well-written and informative blog. Keep sharing more.
    Artificial Intelligence Course

    ReplyDelete
  48. Tremendous blog quite easy to grasp the subject since the content is very simple to understand. Obviously, this helps the participants to engage themselves in to the subject without much difficulty. Hope you further educate the readers in the same manner and keep sharing the content as always you do.

    data science course in faridabad

    ReplyDelete
  49. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    digital marketing courses in hyderabad with placement

    ReplyDelete
  50. Youre so cool! I dont suppose Ive read anything like this before. So nice to search out any individual with some original thoughts on this subject. realy thank you for starting this up. this website is one thing that’s wanted on the web, somebody with a bit of originality. useful job for bringing something new to the internet! Unique Dofollow Backlinks

    ReplyDelete
  51. I love to have this kind of information. Click Here

    ReplyDelete
  52. I truly like you're composing style, incredible data, thankyou for posting.
    data science training

    ReplyDelete
  53. Very interesting blog,Keep sharing such type of post.

    Web-designing Course in Pune

    ReplyDelete
  54. Great to become visiting your weblog once more, it has been a very long time for me. Pleasantly this article i've been sat tight fosuch a long time. I will require this post to add up to my task in the school, and it has identical subject along with your review. Much appreciated, great offer. data science course in nagpur

    ReplyDelete
  55. I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra. data science course in vadodara

    ReplyDelete
  56. Your blog has always attracted me and this particular post left me speechless. It is one of the best pieces of writing I have seen. Good job.....
    emailer design

    ReplyDelete
  57. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data scientist course in delhi

    ReplyDelete
  58. What a really awesome post this is. Truly, one of the best posts I've ever witnessed to see in my whole life. Wow, just keep it up.
    data scientist course in malaysia

    ReplyDelete
  59. Amazing information i really enjoyed reading this wonderful info i have also bookmarked this blog more interesting post like this
    gossipmouth
    flippzilla

    ReplyDelete
  60. I am stunned by the information that you have on this blog. It shows how well you fathom this subject.
    data scientist certification malaysia

    ReplyDelete
  61. I used to be able to find good advice from your blog articles. | www.hairsalonmanhattanbeach.com

    ReplyDelete
  62. Good content and Knowledgeable to all. Keep sharing some more postings with us.
    AI Patasala Python in Hyderabad

    ReplyDelete
  63. Ucuz, kaliteli ve organik sosyal medya hizmetleri satın almak için Ravje Medyayı tercih edebilir ve sosyal medya hesaplarını hızla büyütebilirsin. Ravje Medya ile sosyal medya hesaplarını organik ve gerçek kişiler ile geliştirebilir, kişisel ya da ticari hesapların için Ravje Medyayı tercih edebilirsin. Ravje Medya internet sitesine giriş yapmak için hemen tıkla: www.ravje.com

    İnstagram takipçi satın almak için Ravje Medya hizmetlerini tercih edebilir, güvenilir ve gerçek takipçilere Ravje Medya ile ulaşabilirsin. İnstagram takipçi satın almak artık Ravje Medya ile oldukça güvenilir. Hemen instagram takipçi satın almak için Ravje Medyanın ilgili sayfasını ziyaret et: instagram takipçi satın al

    Tiktok takipçi satın al istiyorsan tercihini Ravje Medya yap! Ravje Medya uzman kadrosu ve profesyonel ekibi ile sizlere Tiktok takipçi satın alma hizmetide sunmaktadır. Tiktok takipçi satın almak için hemen tıkla: tiktok takipçi satın al

    İnstagram beğeni satın almak için Ravje medya instagram beğeni satın al sayfasına giriş yap, hızlı ve kaliteli instagram beğeni satın al: instagram beğeni satın al

    Youtube izlenme satın al sayfası ile hemen youtube izlenme satın al! Ravje medya kalitesi ile hemen youtube izlenme satın almak için tıklayın: youtube izlenme satın al

    Twitter takipçi satın almak istiyorsan Ravje medya twitter takipçi satın al sayfasına tıkla, Ravje medya güvencesi ile organik twitter takipçi satın al: twitter takipçi satın al

    ReplyDelete
  64. Thanks for posting the best information and the blog is very good.data science course in Lucknow

    ReplyDelete
  65. Thanks for ones marvelous posting! I really enjoyed reading it, you might be a great author.
    I will be sure to bookmark your blog and will eventually come back later on.
    Just visit our webpage on visiting card printing for more

    ReplyDelete
  66. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
    data science course in malaysia

    ReplyDelete
  67. Nice Blog !
    Here We are Specialist in Manufacturing of Movies, Gaming, Casual, Faux Leather Jackets, Coats And Vests See. Mr Robot Jacket

    ReplyDelete

  68. Research Paper Ideas, a list of 400+ ideas. I'll also help you make a choice by detecting specific angles. Create a personal shortlist by selecting three research paper topics that you can probably use. For now, just build a rough inventory. Browse this website for more information about research paper idea services.

    ReplyDelete

  69. Are you searching for an assignment helper in the UAE? Then don’t worry! We provide you the best assignment writing services at very cheap prices. Visit our website for help with your work.

    ReplyDelete
  70. Thank you for your post. I sincerely thank you for your post. If you are interested in purchasing our products, you can contact us through this website Custom Boxes With Logo.

    ReplyDelete
  71. This comment has been removed by the author.

    ReplyDelete
  72. Your work is very important to me so I liked it. If you like pets you can see here Wild Animals.

    ReplyDelete
  73. Am very much excited to have visited this awesome bog, this a very exciting blog, fell in love with your amazing design and informative contents. Thanks for sharing. eastern polytechnic (EP) post utme form closing date

    ReplyDelete
  74. All kittens adopted from royaltykitten.com Sphynx Cattery come with current vaccinations, dewormings, written sales contract, Two year health guarantee, health record, Spayed or Neutered, 30 days of free pet insurance for your kitten,
    sphynx cats for sale, sphynx kittens for sale, hairless kitten for sale, hairless cats for sale, and a kitten care package which includes food, litter and several surprises for you and your kitten. sphynx cat for sale near me, sphynx kitten for sale, hairless cats for sale near me, hairless kitten for sale, hairless cats for sale Kittens are Generally ready to leave between 10 to 11 weeks old.
    Sphynx do not develop as quickly as cats with hair.

    ReplyDelete
  75. Hello Yorkies From Elvis Yorkshire Terrier - Specializing in Teacup Yorkies
    We are small breeders whose goal is to produce healthy, high quality little teacup size Yorkie puppies for sale. In order to have puppies for sale most of the time we have teamed up with a couple of other Yorkie breeders that have the same goals in mine. In fact we have some of their Yorkie breeders and they have some of our breeders.
    yorkies for sale, teacup yorkie puppies for sale, Yorkie puppies for sale,

    ReplyDelete
  76. We Provide German Language Classes in pune & <a href="https://www.yesgermany.com/german-language>German Language Course in india</a>

    ReplyDelete