RGB转换为黑色&安培;怀特在OpenCV中 [英] Convert RGB to Black & White in OpenCV

查看:140
本文介绍了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, 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 成灰度图像:否则,你将不得不pviously获得RGB图像$ P $转换成灰度图像。

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。转换为二进制
您可以使用<一个href=\"http://opencv.willowgarage.com/documentation/image_processing.html?highlight=adaptivethreshold#cvAdaptiveThreshold\">adaptive阈值或<一个href=\"http://opencv.willowgarage.com/documentation/image_processing.html?highlight=threshold#cvThreshold\">fixed-level阈值您的灰度图像转换为二进制图像。

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

例如。用C,你可以做以下(你也可以垫做同样的在C ++和相应的功能):

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);

这篇关于RGB转换为黑色&安培;怀特在OpenCV中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆