OpenCV example to convert RGB to gray / other color spaces

void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0 )
Parameters:
  • src – input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point.
  • dst – output image of the same size and depth as src.
  • code – color space conversion code (see the description below).
  • dstCn – number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code .
Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed).

The conventional ranges for R, G, and B channel values are:
  • 0 to 255 for CV_8U images
  • 0 to 65535 for CV_16U images
  • 0 to 1 for CV_32F images


RGB \leftrightarrow GRAY ( CV_BGR2GRAY, CV_RGB2GRAY, CV_GRAY2BGR, CV_GRAY2RGB )
RGB \leftrightarrow YCrCb JPEG (or YCC) ( CV_BGR2YCrCb,CV_RGB2YCrCb,CV_YCrCb2BGR,CV_YCrCb2RGB )
RGB \leftrightarrow HSV ( CV_BGR2HSV, CV_RGB2HSV, CV_HSV2BGR, CV_HSV2RGB )
RGB \leftrightarrow HLS ( CV_BGR2HLS, CV_RGB2HLS, CV_HLS2BGR, CV_HLS2RGB )
RGB \leftrightarrow CIE L*a*b* ( CV_BGR2Lab, CV_RGB2Lab, CV_Lab2BGR, CV_Lab2RGB )
RGB \leftrightarrow CIE L*u*v* ( CV_BGR2Luv, CV_RGB2Luv, CV_Luv2BGR, CV_Luv2RGB )
Bayer \rightarrow RGB ( CV_BayerBG2BGR, CV_BayerGB2BGR, CV_BayerRG2BGR, CV_BayerGR2BGR, CV_BayerBG2RGB, CV_BayerGB2RGB, CV_BayerRG2RGB, CV_BayerGR2RGB )
RGB \leftrightarrow CIE XYZ.Rec 709 with D65 white point ( CV_BGR2XYZ, CV_RGB2XYZ, CV_XYZ2BGR, CV_XYZ2RGB )

Steps:

  1. Load an image 
  2. Convert to gray scale
  3. Show result

Functions:

Example:

-------------
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "iostream"

using namespace cv;
using namespace std;

int main( )
{

       Mat image;
       image = imread("lena.jpg", CV_LOAD_IMAGE_COLOR);  

       if(! image.data )                             
       {
              cout <<  "Could not open or find the image" << std::endl ;
              return -1;
       }

       // Create a new matrix to hold the gray image
       Mat gray;

       // convert RGB image to gray
       cvtColor(image, gray, CV_BGR2GRAY);

       namedWindow( "Display window", CV_WINDOW_AUTOSIZE );  
       imshow( "Display window", image );                 

       namedWindow( "Result window", CV_WINDOW_AUTOSIZE );   
       imshow( "Result window", gray );

       waitKey(0);                                          
       return 0;
}
-------------


Sources:

34 comments:

  1. Hi
    I want to use cvtColor function to convert RGB to HSV but unfortunately I have only cvCvtColor funtions and when I use it I face this ERROR:

    error C2664: 'cvCvtColor' : cannot convert parameter 1 from 'cv::Mat' to 'const CvArr *'

    can someone help me?

    ReplyDelete
    Replies
    1. you only convert 2 images have same type, Mat or IplImage

      Delete
    2. Learn Opencv By Examples: Opencv Example To Convert Rgb To Gray / Other Color Spaces >>>>> Download Now

      >>>>> Download Full

      Learn Opencv By Examples: Opencv Example To Convert Rgb To Gray / Other Color Spaces >>>>> Download LINK

      >>>>> Download Now

      Learn Opencv By Examples: Opencv Example To Convert Rgb To Gray / Other Color Spaces >>>>> Download Full

      >>>>> Download LINK 9w

      Delete
  2. Thank you so much for the code. It helped me to rectify my one silly mistake!

    ReplyDelete
    Replies
    1. I want to share this great testimony to the world on how Dr VOODOO cure me from HSV1&2 with his herbs, I was nervous when i first contact him about the cure for HSV but i decided to give him a try because i was desperate to get cured and be free from HSV. Dr VOODOO prepared the remedy and sent it to me through UPS,which I use just the way Dr VOODOO instructed me and thank God today I am a beneficiary to this cure and I went back to the hospital after 7 days of taking the herbs and I tested HSV1&2 Negative. So I will tell you all who are looking for a cure to his/her HSV1&2 that Dr VOODOO took research before he could finally get the solution to it and a lot of people are benefiting from him right now. He also cured my friend from HPV. Dr VOODOO heals with natural herbs. Please I urge you to contact him now through his email address: voodoospelltemple66@gmail.com or call and WhatsApp him on +2348140120719. He is capable of curing HIV/AIDS, HERPES, HPV, HSV1&2, CANCER of all kinds, DIABETES and so many other infections.

      Delete
  3. can we use cvtColor function to convert binary image to RGB image

    ReplyDelete
    Replies
    1. There is no option for that in the cvtColor function. But you can first convert the image to a gray color image( read some papers for this) then convert to color.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. i have a little prob for example when i use imshow , it says that it's undefined ? haw can i fix this please

    ReplyDelete
    Replies
    1. by adding "cv::" before imshow if u're working with ROS

      Delete
  6. Afraid not. https://usersnap.com/blog/programming-languages-2018/

    ReplyDelete
  7. [ ] I'm here to testify about the great work Dr Osebor did for me. I have been suffering from (HERPES) disease for the past 5 years and had constant pain, especially in my knees. During the first year,I had faith in God that i would be healed someday.This disease started circulating all over my body and i have been taking treatment from my doctor, few weeks ago I came across a testimony of one lady on the internet testifying about a Man called Dr Osebor on how he cured her from HIV Virus. And she also gave the email address of this man and advise anybody to contact Dr Osebor for help for any kind of sickness that he would be of help, so I emailed him on ( oseborwinbacktemple@gmail.com ) telling him about my (HERPES Virus) he told me not to worry that i was going to be cured!! Well i never believed it,, well after all the procedures and remedy given to me by this man few weeks later i started experiencing changes all over me as Dr Osebor assured me that i will be cured,after some time i went to my doctor to confirmed if i have be finally healed behold it was TRUE, So 
    - [ ] friends my advise is if you have such sickness or any other at all you can contact Dr Osebor via email. { oseborwinbacktemple@gmail.com }or call or what sapp him on( +2348073245515 )
    - [ ] DR osebor CAN AS WELL CURE THE FOLLOWING DISEASE:-
    - [ ]  HIV/AIDS
    - [ ]  HERPES
    - [ ] CANCER
    - [ ] ALS
    - [ ] cancer 
    - [ ] Diabetes
    eye problem etc.

    ReplyDelete
  8. Blank ATM Cards
    Do you know that you can hack any ATM machine !!!

    We have specially programmed ATM cards that can be used to hack any ATM machine, this ATM cards can be used to withdraw cash at the ATM or swipe, stores and outlets. We sell this cards to all our customers and interested buyers worldwide, the cards has a daily withdrawal limit of 5000 in ATM and up to 100,000 spending limit in it stores. We also offer the following services:
    1)WESTERN UNION TRANSFERS/MONEY GRAM TRANSFER
    2)BANKS LOGINS
    3)BANKS TRANSFERS
    4)CRYPTOCURRENCY MINING
    5)BUYING OF GIFT CARDS
    6)LOADING OF ACCOUNTS
    7)WALMART TRANSFERS
    8)BITCOIN INVESTMENTS
    9)REMOVING OF NAME FROM DEBIT RECORD AND CRIMINAL RECORD
    10)BANK HACKING

     Becoming wealthy and living the lifestyle of the rich and famous is the dream of many people. And whilst most people go to work or seek other ethical methods of making money online.
     The blank ATM withdraws money from any ATM machines and there is no name on it because it is blank just your PIN will be on it, it is not traceable and now I have money for business, shopping and enough money for me and my family to live on.
     PROGRAMMED blank ATM card that is capable of hacking into any ATM machine,anywhere in the world.
      Contact Person: Prof Alexander Castro
      E-Mail: atmservices44@aol.com
      E-Mail: atmservices44@yahoo.com

    ReplyDelete
  9. I DON'T BUY BITCOIN, I EARN IT DAILY FROM MY INVESTMENTS WITH A RELIABLE PLATFORM.
    ✅ NO REGISTRATION FEE
    ✅ INSTANT WITHDRAWAL
    ✅ 5% TO 10% REFERRAL BONUS IF INTERESTED.
    I EARN MORE THAN $400 DAILY WITH THIS PLATFORM AND IT IS 100% SAFE AND GUARANTEED. TESTIFY THE RELIABILITY OF THE PLATFORM YOURSELF WHEN YOU SIGN UP AND EARN.
    CONTACT ME IF YOU WANT TO MAKE MONEY WITH BITCOIN VIA WHATSAPP +44 7451 272215 OR EMAIL; bitcoinzone.info@gmail.com AND I WILL SHARE THE WEBSITE WITH YOU TO
    START EARNING.

    ReplyDelete
  10. You have written an excellent article here. It is great to have access to your blog to read more articles. Are you familiar with Tap BPM? In other words, the BPM stands for beats per minute or the tempo of a piece of music. On my blog, you can find more information.

    ReplyDelete
  11. Very informative. To activate Mcafee security, go to
    Mcafee activate. Details of the whole process is given in this link.

    ReplyDelete

  12. I was impressed with your writing style after reading a few articles in your online magazine.
    You can learn more about Free Auto Clicker in profile Auto Mouse Clicker if you don't know about it. Thank you for your concern.

    ReplyDelete
  13. Do you need Finance? Are you looking for Finance? Are you looking for finance to enlarge your business? We help individuals and companies to obtain finance for business expanding and to setup a new business ranging any amount. Get finance at affordable interest rate of 3%, Do you need this finance for business and to clear your bills? Then send us an email now for more information contact us now via (financialserviceoffer876@gmail.com) whats-App +918929509036 Dr James Eric Finance Pvt Ltd Thanks

    ReplyDelete
  14. https://gamebegin.xyz You are able to process alone. A pitching machine permits you to established the rate of your ball. By loading several baseballs in the machine, you are able to practice striking without needing a pitcher. This electronic digital device is ideal for all those who want to process baseball alone. Pitching devices might be found at your community wearing items store.

    ReplyDelete
  15. https://gameboot.xyz You see them on periodicals and so on Tv set, people who appear to be their forearms and thighs and legs will explode since their muscle groups are so large! There is not any will need that you can get your body for that level in the event you don't want to, since the basic tactics in the following paragraphs will enable you to build muscle mass within a healthy approach.

    ReplyDelete
  16. https://gamezoom.xyz Obtaining a work out partner can significantly improve your muscle tissue-constructing results. Your partner might be a important supply of determination for staying on your workout session, and driving one to optimize your efforts whilst you exercise. Possessing a trustworthy lover to sort out with will also help help keep you safe as you will always have got a spotter.

    ReplyDelete
  17. I am a living testimony of change. I can safely say that i have been blessed and my life transformed from being just a company attendant to a business owner all in the space of 1 month after i got my return on investment from davidbenjaminexptrader@outlook.com I did try some other trader but i got scammed. I am using this medium to reach out to the world for those who got plans to go bigger and better in life to contact this company via davidbenjaminexptrader@outlook.com or on WhatsApp +1 408 500 0775
    asap for certified and trusted services.

    ReplyDelete
  18. Learn Opencv By Examples: Opencv Example To Convert Rgb To Gray / Other Color Spaces >>>>> Download Now

    >>>>> Download Full

    Learn Opencv By Examples: Opencv Example To Convert Rgb To Gray / Other Color Spaces >>>>> Download LINK

    >>>>> Download Now

    Learn Opencv By Examples: Opencv Example To Convert Rgb To Gray / Other Color Spaces >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete
  19. Thank you for providing such valuable content! Your guide was perfect, and 123 hp com setup filled in any extra details I needed.

    ReplyDelete