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

#include<iostream>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\core\core.hpp>
#include <opencv2\imgproc\imgproc.hpp>

using namespace std;
using namespace cv;

int main()
{
	Mat img, imgGray,result;
	img = imread("test.jpg");
	if (!img.data) {
		cout << "Please input image path" << endl;
		return 0;
	}
	imshow("原圖", img);
	cvtColor(img, imgGray, CV_BGR2GRAY);
	imshow("灰度圖", imgGray);
	//blur(imgGray, imgGray, Size(3, 3));
	threshold(imgGray, result, 100, 255, CV_THRESH_BINARY);
	imshow("二值化後的圖", result);
	imwrite("二值化的二維碼.jpg", result);
	cout << "圖片已保存" << endl;
	waitKey();

    return 0;
}

四、效果:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章