Convert image document to black and white with OpenCV

℡╲_俬逩灬. 提交于 2019-12-01 00:53:17

My attemp, maybe a little more readable than yours:

IplImage * pRGBImg  = 0;
pRGBImg = cvLoadImage(input_file.c_str(), CV_LOAD_IMAGE_UNCHANGED);
if(!pRGBImg)
{   
    std::cout << "ERROR: Failed to load input image" << std::endl;
    return -1; 
}   

// Allocate the grayscale image
IplImage * pGrayImg = 0;
pGrayImg = cvCreateImage(cvSize(pRGBImg->width, pRGBImg->height), pRGBImg->depth, 1); 

// Convert it to grayscale
cvCvtColor(pRGBImg, pGrayImg, CV_RGB2GRAY);

// Dilate
cvDilate(pGrayImg, pGrayImg, 0, 0.2);

cvThreshold(pGrayImg, pGrayImg, 30, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
cvSmooth(pGrayImg, pGrayImg, CV_BLUR, 2, 2);

cvSaveImage("out.png", pGrayImg);

Threshold image is used for different purposes.

If u just want to convert it to b/w image just do this. USing openCV 2.2

cv::Mat image_name = cv::imread("fileName", 0);

the second parameter 0 tells to read a color image as b/w image.

And if you want to save as a b/w image file.

code this

cv::Mat image_name = cv::imread("fileName", 0);
cv::imwrite(image_name, "bw_filename.jpg");

Using Adaptive Gaussian Thresholding is a good idea here. This will also enhance the quality of text written in the image. You can do that by simply giving the command:

AdaptiveThreshold(src_Mat, dst_Mat, Max_value, Adaptive_Thresholding_Method, Thresholding_type, blocksize, C);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!