问题描述
我正在构建文档扫描仪应用程序,需要检测图像中文档的角点以进行裁剪。 到目前为止,我的代码仅在图像背景较暗时有效。 但我想在所有背景下使用它。
这是我的代码
vector<Point> getPoints(Mat image)
{
int width = image.size().width;
int height = image.size().height;
Mat image_proc = image.clone();
vector<vector<Point> > squares;
// blur will enhance edge detection
Mat blurred(image_proc);
cvtColor(image_proc,image_proc,CV_BGR2GRAY);
medianBlur(image_proc,blurred,9);
Mat gray0(blurred.size(),CV_8U),gray;
vector<vector<Point> > contours;
// find squares in every color plane of the image
for (int c = 0; c < 3; c++)
{
int ch[] = {c,0};
mixChannels(&blurred,1,&gray0,ch,1);
// try several threshold levels
const int threshold_level = 2;
for (int l = 0; l < threshold_level; L++)
{
// Use Canny instead of zero threshold level!
// Canny helps to catch squares with gradient shading
if (l == 0)
{
Canny(gray0,gray,10,20,3); //
// Dilate helps to remove potential holes between edge segments
dilate(gray,Mat(),Point(-1,-1));
}
else
{
gray = gray0 >= (l+1) * 255 / threshold_level;
}
// Find contours and store them in a list
findContours(gray,contours,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
// Test contours
vector<Point> approx;
for (size_t i = 0; i < contours.size(); i++)
{
// approximate contour with accuracy proportional
// to the contour perimeter
approxpolyDP(Mat(contours[i]),approx,arcLength(Mat(contours[i]),true)*0.02,true);
// Note: absolute value of an area is used because
// area may be positive or negative - in accordance with the
// contour orientation
if (approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for (int j = 2; j < 5; j++)
{
double cosine = fabs(angle(approx[j%4],approx[j-2],approx[j-1]));
maxCosine = MAX(maxCosine,cosine);
}
if (maxCosine < 0.3)
squares.push_back(approx);
}
}
}
double largest_area = -1;
int largest_contour_index = 0;
for(int i=0;i<squares.size();i++)
{
double a =contourArea(squares[i],false);
if(a>largest_area)
{
largest_area = a;
largest_contour_index = i;
}
}
__android_log_print(ANDROID_LOG_VERBOSE,APPNAME,"Scaning size() %d",squares.size());
vector<Point> points;
if(squares.size() > 0)
{
points = squares[largest_contour_index];
}
else
{
points.push_back(Point(0,0));
points.push_back(Point(width,0));
points.push_back(Point(0,height));
points.push_back(Point(width,height));
}
return points;
}
上面的函数返回图像内文档的角。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)