资源简介
将图像直方图进行平滑,获得双峰分布形式,并通过双峰特性进行图像二值化。opencv3.1.0, vs2015。
代码片段和文件信息
#include
#include
#include
using namespace cv;
using namespace std;
#define HISTGRAM_X_SCALE 2
#define HISTGRAM_X_SIZE (256*HISTGRAM_X_SCALE)
#define HISTGRAM_Y_SIZE 400
void doSomething(Mat src);
void showHistgram(int *grayLevel string windowName);
int smoothHistgram(int *oldHist double *newHist);
bool isTwoPolar(double *hist);
uchar findLocalMinimum(double *hist);
#define MAX_PICTURE_NUMBER 100
string FILE_SOURCE_PATH = “nearBall\\“;
void main() {
Mat src;
int i = 0;
string no;
for (int i = 0; i < MAX_PICTURE_NUMBER; ++i) {
if (i < 0)
i = 0;
no = to_string(i);
src = imread(FILE_SOURCE_PATH + no + “.jpg“ 1);
if (src.empty())
cout << endl << “ERROR“ << endl;
imshow(“原图“ src);
doSomething(src);
int keyValue = waitKey(0);
switch (keyValue) {
case ‘w‘: case ‘a‘:
i--;
break;
case ‘b‘:
i = 0;
break;
case ‘q‘:
return;
default:
i++;
break;
}
}
return;
}
void doSomething(Mat src) {
Mat grayImg;
int grayLevel[256] = { 0 };
if (src.type() != CV_8UC1)
cvtColor(src grayImg CV_BGR2GRAY);
imshow(“灰度图“ grayImg);
// 统计灰度分布
for (int i = 0; i < src.rows; ++i) {
for (int j = 0; j < src.cols; ++j) {
uchar value = src.at(i j);
grayLevel[value]++;
}
}
showHistgram(grayLevel “Original“);
double newHist[256] = { 0 };
if (smoothHistgram(grayLevel newHist) != -1) {
uchar p1 p2;
int intHist[256] = { 0 };
for (int i = 0; i < 256; ++i)
intHist[i] = static_cast(newHist[i]);
showHistgram(intHist “New“);
int thresh = findLocalMinimum(newHist);
Mat binImg;
threshold(grayImg binImg thresh 255 THRESH_BINARY);
imshow(“二值化图“ binImg);
}
else
;
// 绘制平滑直方图
}
void showHistgram(int *grayLevel string windowName = “Default“) {
double minValue = *min_element(grayLevel grayLevel + 256);
double maxValue = *max_element(grayLevel grayLevel + 256);
//cout << “Min: “ << minValue << “ Max: “ << maxValue << endl;
Mat d
评论
共有 条评论