opencv基础-实现图像阈值化
阈值化函数原型
double threshold( InputArray src, OutputArray dst,
double thresh, double maxval, int type );
其中type包含如下:
enum { THRESH_BINARY=CV_THRESH_BINARY, THRESH_BINARY_INV=CV_THRESH_BINARY_INV,
THRESH_TRUNC=CV_THRESH_TRUNC, THRESH_TOZERO=CV_THRESH_TOZERO,
THRESH_TOZERO_INV=CV_THRESH_TOZERO_INV, THRESH_MASK=CV_THRESH_MASK,
THRESH_OTSU=CV_THRESH_OTSU };
各种type的具体操作如下
template <typename T>
static inline T threshBinary(const T& src, const T& thresh, const T& maxval)
{
return src > thresh ? maxval : 0;
}
template <typename T>
static inline T threshBinaryInv(const T& src, const T& thresh, const T& maxval)
{
return src <= thresh ? maxval : 0;
}
template <typename T>
static inline T threshTrunc(const T& src, const T& thresh)
{
return std::min(src, thresh);
}
template <typename T>
static inline T threshToZero(const T& src, const T& thresh)
{
return src > thresh ? src : 0;
}
template <typename T>
static inline T threshToZeroInv(const T& src, const T& thresh)
{
return src <= thresh ? src : 0;
}
template <typename T>
static void threshGeneric(Size roi, const T* src, size_t src_step, T* dst,
size_t dst_step, T thresh, T maxval, int type)
{
int i = 0, j;
switch (type)
{
case THRESH_BINARY:
for (; i < roi.height; i++, src += src_step, dst += dst_step)
for (j = 0; j < roi.width; j++)
dst[j] = threshBinary<T>(src[j], thresh, maxval);
return;
case THRESH_BINARY_INV:
for (; i < roi.height; i++, src += src_step, dst += dst_step)
for (j = 0; j < roi.width; j++)
dst[j] = threshBinaryInv<T>(src[j], thresh, maxval);
return;
case THRESH_TRUNC:
for (; i < roi.height; i++, src += src_step, dst += dst_step)
for (j = 0; j < roi.width; j++)
dst[j] = threshTrunc<T>(src[j], thresh);
return;
case THRESH_TOZERO:
for (; i < roi.height; i++, src += src_step, dst += dst_step)
for (j = 0; j < roi.width; j++)
dst[j] = threshToZero<T>(src[j], thresh);
return;
case THRESH_TOZERO_INV:
for (; i < roi.height; i++, src += src_step, dst += dst_step)
for (j = 0; j < roi.width; j++)
dst[j] = threshToZeroInv<T>(src[j], thresh);
return;
default:
CV_Error( CV_StsBadArg, "" ); return;
}
}
opencv代码写得真棒
阈值化所有代码:
#include <opencv2\opencv.hpp>
#include <opencv\highgui.h>
#include <iostream>
#include <algorithm>
using namespace std;
using namespace cv;
int main()
{
const string dstName = "";
Mat img = imread(dstName, 3);
cout << img.rows << endl;
Mat dst;
threshold(img, dst, 20, 255, 1);
//namedWindow("test");
imshow("name", dst);
waitKey(0);
system("pause");
return 0;
}