OpenCV图像处理:灰度化和二值化


一、图像二值化基本原理:
对灰度图像进行处理,设定阈值,在阈值中的像素值将变为1(白色部分),阈值为的将变为0(黑色部分)。

二、图像二值化处理步骤:

(1)先对彩色图像进行灰度化

//img为原图,imgGray为灰度图
cvtColor(img, imgGray, CV_BGR2GRAY);

(2)对灰度图进行二值化

//imgGray为灰度图,result为二值图像 //100~255为阈值,可以根据情况设定 //在阈值中的像素点将变为0(白色部分),阈值之外的像素将变为1(黑色部分)。
threshold(imgGray, result, 100, 255, CV_THRESH_BINARY)

三、demo

 1 #include<iostream>
 2 #include<opencv2\highgui\highgui.hpp>
 3 #include<opencv2\core\core.hpp>
 4 #include <opencv2\imgproc\imgproc.hpp>
 5  
 6 using namespace std;  7 using namespace cv;  8  
 9 int main() 10 { 11  Mat img, imgGray,result; 12     img = imread("test.jpg"); 13     if (!img.data) { 14         cout << "Please input image path" << endl; 15         return 0; 16  } 17     imshow("原图", img); 18  cvtColor(img, imgGray, CV_BGR2GRAY); 19     imshow("灰度图", imgGray); 20     //blur(imgGray, imgGray, Size(3, 3));
21     threshold(imgGray, result, 100, 255, CV_THRESH_BINARY); 22     imshow("二值化后的图", result); 23     imwrite("二值化的二维码.jpg", result); 24     cout << "图片已保存" << endl; 25  waitKey(); 26  
27     return 0; 28 }

四、效果:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM