图像二值化就是将【0,255】之间的灰度数据通过门限值(K)变换为{0,255}的一个数据集合
最简单的方法是取值 K = 127,简单粗暴
或者取值 K = avg(pixels) (像素平均值)
#include "JpegDecoder.h"
#include
#include
#include
using namespace JpegCodec;
static cv::Mat ConvertToMat(Matrix &mat)
{
int channel = CV_8UC3;
if (mat.channal == 1) channel = CV_8UC1;
cv::Mat img(mat.rows, mat.cols, channel); // create a new matrix
for (int i = 0; i < mat.rows * mat.cols * mat.channal; i++)
{
img.data[i] = mat.data[i];
}
return img;
}
方案一 K = 127
//void Binary(Matrix &mat)
//{
//for (int i = 0; i < mat.rows * mat.cols * mat.channal; i++)
//{
//if (mat.data[i] < 127) mat.data[i] = 0;
//else mat.data[i] = 255;
//}
//}
方案二 K = avg(pixels)
//void Binary(Matrix &mat)
//{
//int avg = 0;
//int cnt = mat.rows * mat.cols * mat.channal;
//for (int i = 0; i < cnt; i++)
//{
//avg += mat.data[i];
//}
//avg = avg / cnt;
//
//for (int i = 0; i < cnt; i++)
//{
//if (mat.data[i] < avg) mat.data[i] = 0;
//else mat.data[i] = 255;
//}
//}
void ShowImage(Matrix &mat)
{
cv::Mat img = ConvertToMat(mat);
cv::imshow("Bitmap", img);
}
// 图像灰度化
void Gray(Matrix &dst, Matrix &src)
{
dst.Create(src.rows, src.cols, 1);
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
int idx = (i * src.rows + j) * 3;
dst.data[idx / 3] = (src.data[idx] + src.data[idx + 1] + src.data[idx + 2]) / 3;
}
}
}
int main(int argc, char *arrv[])
{
JpegDecoder decoder("01.jpg");
Matrix mat, dst;
decoder.Decoder(mat);
Gray(dst, mat);
Binary(dst);
ShowImage(dst);
cvWaitKey(0);
return 0;
}
运行示例
灰度图
K = 127
K = avg(pixels)