void projection4ruler(Mat src, int& down1,int& up2 ,int direction){
Mat tmp = src.clone();
vector<int> vdate;
if (DIRECTION_X == direction){
for (int i=0;i<tmp.cols;i++){
Mat data = tmp.col(i);
int itmp = countNonZero(data);
if (itmp > 10)
{
int jjj=0;
}
vdate.push_back(itmp);
}
}else{
for (int i=0;i<tmp.rows;i++){
Mat data = tmp.row(i);
int itmp = countNonZero(data);
vdate.push_back(itmp);
}
}
//过滤掉所有噪音
//寻找第一个下边沿和第二个上边沿
down1 = 1;
up2 = src.cols - 1;
for (int i=0;i<tmp.cols-1;i++)
{
if (vdate[i] >= 100 && vdate[i+1] < 100)
{
down1 = i;
break;
}
}
for (int i= down1;i<tmp.cols - 1;i++)
{
if (vdate[i] < 100 && vdate[i+1] >= 100)
{
up2 = i;
return;
}
}
}
//GoCvHelper的demo程序
#include "stdafx.h"
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "GoCvHelper.h"
using namespace std;
using namespace cv;
using namespace GO;
#define VP vector<cv::Point> //用VP符号代替 vector<point>
void projection4ruler(Mat src, int& down1,int& up2 ,int direction){
Mat tmp = src.clone();
vector<int> vdate;
if (DIRECTION_X == direction){
for (int i=0;i<tmp.cols;i++){
Mat data = tmp.col(i);
int itmp = countNonZero(data);
if (itmp > 10)
{
int jjj=0;
}
vdate.push_back(itmp);
}
}else{
for (int i=0;i<tmp.rows;i++){
Mat data = tmp.row(i);
int itmp = countNonZero(data);
vdate.push_back(itmp);
}
}
//过滤掉所有噪音
//寻找第一个下边沿和第二个上边沿
down1 = 1;
up2 = src.cols - 1;
for (int i=0;i<tmp.cols-1;i++)
{
if (vdate[i] >= 100 && vdate[i+1] < 100)
{
down1 = i;
break;
}
}
for (int i= down1;i<tmp.cols - 1;i++)
{
if (vdate[i] < 100 && vdate[i+1] >= 100)
{
up2 = i;
return;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Mat src = imread("E:\\sandbox\\1.bmp");
Mat dst;
Mat tmp;
int up1 = 0;
int down2 = 0;
vector<Mat> matSplit;
cvtColor(src,tmp,COLOR_BGR2Lab);
split(tmp,matSplit);
dst = matSplit[1];
threshold(dst,dst,100,255,THRESH_OTSU);
threshold(dst,dst,0,255,THRESH_BINARY_INV);//以白色为有数据
projection4ruler(dst,up1,down2,DIRECTION_X);
line(src,Point(up1,0),Point(up1,src.rows-1),Scalar(0,0,255),1);
line(src,Point(down2,0),Point(down2,src.rows-1),Scalar(0,0,255),1);
cv::waitKey();
return 0;
}