Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGB to Black & White in OpenCV

I would like to know how to convert an RGB image into a black & white (binary) image.

After conversion, how can I save the modified image to disk?

like image 903
mohammed Avatar asked Oct 18 '09 17:10

mohammed


People also ask

How do I convert a color image to grayscale?

Change a picture to grayscale or to black-and-whiteRight-click the picture that you want to change, and then click Format Picture on the shortcut menu. Click the Picture tab. Under Image control, in the Color list, click Grayscale or Black and White.

Why is RGB gray?

The RGB scale is calibrated so that when a color's three red/green/blue numbers are equal, the color is a shade of gray. E.g. red=50 green=50 blue=50 is gray, without any bias towards red, green, or blue hue.


2 Answers

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

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

// C IplImage* 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

// C IplImage *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 binary You 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):

// C IplImage* 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

// C cvSaveImage("image_bw.jpg",img_bw);  // C++ imwrite("image_bw.jpg", img_bw); 
like image 194
Jacob Avatar answered Sep 21 '22 17:09

Jacob


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); 
like image 20
nikithashr Avatar answered Sep 17 '22 17:09

nikithashr