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?
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With