这里来说明一下做这次的二维码提取算法用到的函数,最后再给出完整的代码!
进行图像的二值化,这里可以使用opencv2里的函数threshold,当然在opencv里也有cvThreshold函数
(这个函数可以具体参考:http://blog.csdn.net/xuehuic/article/details/7401181)
首先我们要了解:
最简单的图像分割的方法。
应用举例:从一副图像中利用阈值分割出我们需要的物体部分(当然这里的物体可以是一部分或者整体)。这样的图像分割方法是基于图像中物体与背景之间的灰度差异,而且此分割属于像素级的分割。为了从一副图像中提取出我们需要的部分,应该用图像中的每一个像素点的灰度值与选取的阈值进行比较,并作出相应的判断。(注意:阈值的选取依赖于具体的问题。即:物体在不同的图像中有可能会有不同的灰度值。一旦找到了需要分割的物体的像素点,我们可以对这些像素点设定一些特定的值来表示。(例如:可以将该物体的像素点的灰度值设定为:‘0’(黑色),其他的像素点的灰度值为:‘255’(白色);当然像素点的灰度值可以任意,但最好设定的两种颜色对比度较强,方便观察结果)。
OpenCV中提供了阈值(threshold)函数: threshold 。
这个函数有5种阈值化类型。(参考:http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/imgproc/threshold/threshold.html)
举个使用栗子:
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <vector>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <math.h>
using namespace std;
using namespace cv;
/// 全局变量定义及赋值
int threshold_value = 0;
int threshold_type = 3;;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;
Mat src, src_gray, dst;
char* window_name = "Threshold Demo";
char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
char* trackbar_value = "Value";
/// 自定义函数声明
void Threshold_Demo( int, void* );
/**
* @主函数
*/
int _tmain( int argc, char** argv )
{
const char* imagename = "F:\\My_opencv\\as.jpg";
src = imread(imagename,1);
/// 读取一副图片,不改变图片本身的颜色类型
/// 将图片转换成灰度图片
cvtColor( src, src_gray, CV_RGB2GRAY );
/// 创建一个窗口显示图片
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
/// 创建滑动条来控制阈值
createTrackbar( trackbar_type,
window_name, &threshold_type,
max_type, Threshold_Demo );
createTrackbar( trackbar_value,
window_name, &threshold_value,
max_value, Threshold_Demo );
/// 初始化自定义的阈值函数
Threshold_Demo( 0, 0 );
/// 等待用户按键。如果是ESC健则退出等待过程。
while(true)
{
int c;
c = waitKey( 20 );
if( (char)c == 27 )
{ break; }
}
return 0;
}
/**
* @自定义的阈值函数
*/
void Threshold_Demo( int, void* )
{
/* 0: 二进制阈值
1: 反二进制阈值
2: 截断阈值
3: 0阈值
4: 反0阈值
*/
threshold( src_gray, dst, threshold_value, max_BINARY_value,threshold_type );
imshow( window_name, dst );
}