将 RGB 转换为黑色 &OpenCV 中的白色

我想知道如何将 RGB 图像转换为黑色 &白色(二进制)图像.

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?

推荐答案

AFAIK,你必须把它转换成灰度,然后阈值转换成二进制.

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

1.将图像读取为灰度图像如果您是从磁盘读取 RGB 图像,那么您可以直接将其作为灰度图像读取,如下所示:

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.将RGB图像im_rgb转换为灰度图像:否则,您必须将之前获得的RGB图像转换为灰度图像

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.转换为二进制您可以使用自适应阈值或固定级别阈值 将您的灰度图像转换为二值图像.

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

例如在 C 中,您可以执行以下操作(您也可以在 C++ 中使用 Mat 和相应的函数执行相同的操作):

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;

在上面的例子中,128 是阈值.

In the above example, 128 is the threshold.

4.保存到磁盘

// C
cvSaveImage("image_bw.jpg",img_bw);

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

相关文章