我在我的测试应用程序中成功地实现了OpenCV平方检测示例,但现在需要过滤输出,因为它相当混乱-还是我的代码错了?
我感兴趣的是这篇论文的四个角点,用于…的偏斜减少(如that)和进一步处理
输入和输出:
原图:
代码:
double angle( cv::Point pt1, cv::Point pt2, cv::Point pt0 ) {
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
- (std::vector<std::vector<cv::Point> >)findSquaresInImage:(cv::Mat)_image
{
std::vector<std::vector<cv::Point> > squares;
cv::Mat pyr, timg, gray0(_image.size(), CV_8U), gray;
int thresh = 50, N = 11;
cv::pyrDown(_image, pyr, cv::Size(_image.cols/2, _image.rows/2));
cv::pyrUp(pyr, timg, _image.size());
std::vector<std::vector<cv::Point> > contours;
for( int c = 0; c < 3; c++ ) {
int ch[] = {c, 0};
mixChannels(&timg, 1, &gray0, 1, ch, 1);
for( int l = 0; l < N; l++ ) {
if( l == 0 ) {
cv::Canny(gray0, gray, 0, thresh, 5);
cv::dilate(gray, gray, cv::Mat(), cv::Point(-1,-1));
}
else {
gray = gray0 >= (l+1)*255/N;
}
cv::findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
std::vector<cv::Point> approx;
for( size_t i = 0; i < contours.size(); i++ )
{
cv::approxPolyDP(cv::Mat(contours[i]), approx, arcLength(cv::Mat(contours[i]), true)*0.02, true);
if( approx.size() == 4 && fabs(contourArea(cv::Mat(approx))) > 1000 && cv::isContourConvex(cv::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);
}
}
}
}
}
return squares;
}
EDIT 17/08/2012:
要在图像上绘制检测到的方块,请使用以下代码:
cv::Mat debugSquares( std::vector<std::vector<cv::Point> > squares, cv::Mat image )
{
for ( int i = 0; i< squares.size(); i++ ) {
// draw contour
cv::drawContours(image, squares, i, cv::Scalar(255,0,0), 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
// draw bounding rect
cv::Rect rect = boundingRect(cv::Mat(squares[i]));
cv::rectangle(image, rect.tl(), rect.br(), cv::Scalar(0,255,0), 2, 8, 0);
// draw rotated rect
cv::RotatedRect minRect = minAreaRect(cv::Mat(squares[i]));
cv::Point2f rect_points[4];
minRect.points( rect_points );
for ( int j = 0; j < 4; j++ ) {
cv::line( image, rect_points[j], rect_points[(j+1)%4], cv::Scalar(0,0,255), 1, 8 ); // blue
}
}
return image;
}
发布于 2012-01-14 23:10:09
这是Stackoverflow中反复出现的主题,因为我无法找到相关的实现,所以我决定接受挑战。
我对OpenCV中的squares演示进行了一些修改,生成的C++代码能够检测图像中的一张纸:
void find_squares(Mat& image, vector<vector<Point> >& squares)
{
// blur will enhance edge detection
Mat blurred(image);
medianBlur(image, 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, 1, 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, 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);
}
}
}
}
}
执行此过程后,纸张将成为vector<vector<Point> >
中最大的正方形
我让你写一个函数来找出最大的正方形。;)
发布于 2013-01-17 05:56:50
除非有一些其他要求没有指定,我会简单地转换您的彩色图像为灰度和工作只(不需要在3个通道上工作,目前的对比度已经太高了)。此外,除非有一些关于调整大小的特定问题,否则我会使用您的图像的缩小版本,因为它们相对较大,并且大小不会增加正在解决的问题。然后,最后,使用中值滤波器、一些基本的形态学工具和统计(主要用于Otsu阈值,这已经为您完成了)解决了您的问题。
这是我从你的样本图像和其他一些图像中获得的,以及我在周围找到的一张纸:
中值滤波器用于从现在的灰度图像中删除次要细节。它可能会去除白纸内部的细线,这是很好的,因为这样你就会得到很容易丢弃的微小的连接组件。在中值之后,应用形态梯度(简单地说是dilation
- erosion
),并使用Otsu对结果进行二值化。形态梯度是一种很好的保持强边缘的方法,应该得到更多的应用。然后,由于此梯度会增加轮廓宽度,因此应用形态学细化。现在,您可以丢弃小组件。
在这一点上,这是我们所拥有的右图(在绘制蓝色多边形之前),左边的没有显示,因为唯一剩下的组件是描述论文的组件:
考虑到这些示例,现在剩下的唯一问题就是区分看起来像矩形的组件和不像矩形的组件。这是一个确定包含形状的凸壳面积与其边界框面积之间的比率的问题;比率0.7适用于这些示例。可能的情况是,您还需要使用此方法丢弃文件中的组件,而不是这些示例中的组件(然而,执行此步骤应该非常容易,因为它可以直接通过OpenCV完成)。
以下是Mathematica中的示例代码,以供参考:
f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
f = ImageResize[f, ImageDimensions[f][[1]]/4]
g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
h = DeleteSmallComponents[Thinning[
Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
convexvert = ComponentMeasurements[SelectComponents[
h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &],
"ConvexVertices"][[All, 2]]
(* To visualize the blue polygons above: *)
Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5],
Polygon @@ convexvert}]]
如果存在更多不同的情况,其中纸张的矩形定义不是很好,或者该方法将其与其他形状混淆--这些情况可能是由于各种原因造成的,但常见的原因是图像采集不佳--那么尝试将预处理步骤与论文“基于窗口Hough变换的矩形检测”中描述的工作结合起来。
发布于 2017-12-20 11:34:25
好吧,我要迟到了。
在您的图像中,纸张是white
,而背景是colored
。因此,最好在HSV color space
中检测纸张是否为Saturation(饱和度)
通道。请先参考维基HSL_and_HSV。然后,我将从这个Detect Colored Segment in an image中复制我的答案中的大部分想法。
主要步骤:
将图像从通道读入BGR
bgr
hsv
Canny
,或HoughLines
,我选择findContours
),大约获取角点。这是我的结果:
Python代码(Python3.5+ OpenCV 3.3):
#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST
import cv2
import numpy as np
##(1) read into bgr-space
img = cv2.imread("test2.jpg")
##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)
##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)
##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
canvas = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)
## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]
## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)
## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)
相关答案:
https://stackoverflow.com/questions/8667818
复制相似问题