Convert RGB to Black & White in OpenCV Convert RGB to Black & White in OpenCV c c

Convert RGB to Black & White in OpenCV


AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale imageIf you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// CIplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);// C++ (OpenCV 2.0)Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// CIplImage *im_rgb  = cvLoadImage("image.jpg");IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);// C++Mat im_rgb  = imread("image.jpg");Mat im_gray;cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binaryYou can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// CIplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);// C++Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// CcvSaveImage("image_bw.jpg",img_bw);// C++imwrite("image_bw.jpg", img_bw);


This seemed to have worked for me!

Mat a_image = imread(argv[1]);cvtColor(a_image, a_image, CV_BGR2GRAY);GaussianBlur(a_image, a_image, Size(7,7), 1.5, 1.5);threshold(a_image, a_image, 100, 255, CV_THRESH_BINARY);


I do something similar in one of my blog postings. A simple C++ example is shown.

The aim was to use the open source cvBlobsLib library for the detectionof spot samples printed to microarray slides, but the images have to be converted from colour -> grayscale -> black + white as you mentioned, in order to achieve this.