エッジ検出器の出力から短い線分を削除するアルゴリズムを探しています。下の画像 (およびリンク) に見られるように、「長い」線ではないいくつかの小さなエッジが検出されています。理想的には、処理後に四角形の 4 辺だけが表示されるようにしたいのですが、いくつかのはぐれた線がある場合、それは大したことではありません... 何か提案はありますか?
7 に答える
エッジを見つける前に、開く操作または閉じる操作 (またはその両方) を使用してイメージを前処理します。つまり、erodeの後にdilateを実行するか、dilateの後にerodeを実行します。これにより、小さいオブジェクトが削除されますが、大きいオブジェクトはほぼ同じままになります。
オンラインの例を探しましたが、このPDF の 41 ページにあるのが最良の例でした。
これが単純なローカル操作で実行できるとは思えません。保持したい長方形を見てください - いくつかのギャップがあるため、ローカル操作を実行して短い線分を削除すると、おそらく目的の出力の品質が大幅に低下します。
その結果、ギャップを埋めたり、多角形をフィッティングしたりして、四角形を重要なコンテンツとして検出しようとし、次に 2 番目のステップで残りの重要でないコンテンツを破棄します。ハフ変換が役立つかもしれません。
アップデート
サンプル画像でカーネルハフ変換を使用してこのサンプルアプリケーションを使用したところ、長方形に合う4本の素敵な線が得られました.
誰かがこのスレッドに足を踏み入れた場合に備えて、OpenCV 2.x は、 基本的にこのタスクを釘付けにするsquares.cppという名前の例をもたらします。
四角形の検出を改善するために、アプリケーションにわずかな変更を加えました
コード:
#include "highgui.h"
#include "cv.h"
#include <iostream>
#include <math.h>
#include <string.h>
using namespace cv;
using namespace std;
void help()
{
cout <<
"\nA program using pyramid scaling, Canny, contours, contour simpification and\n"
"memory storage (it's got it all folks) to find\n"
"squares in a list of images pic1-6.png\n"
"Returns sequence of squares detected on the image.\n"
"the sequence is stored in the specified memory storage\n"
"Call:\n"
"./squares\n"
"Using OpenCV version %s\n" << CV_VERSION << "\n" << endl;
}
int thresh = 70, N = 2;
const char* wndname = "Square Detection Demonized";
// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
double angle( Point pt1, Point pt2, 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);
}
// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
void findSquares( const Mat& image, vector<vector<Point> >& squares )
{
squares.clear();
Mat pyr, timg, gray0(image.size(), CV_8U), gray;
// karlphillip: dilate the image so this technique can detect the white square,
Mat out(image);
dilate(out, out, Mat(), Point(-1,-1));
// then blur it so that the ocean/sea become one big segment to avoid detecting them as 2 big squares.
medianBlur(out, out, 3);
// down-scale and upscale the image to filter out the noise
pyrDown(out, pyr, Size(out.cols/2, out.rows/2));
pyrUp(pyr, timg, out.size());
vector<vector<Point> > contours;
// find squares only in the first color plane
for( int c = 0; c < 1; c++ ) // was: c < 3
{
int ch[] = {c, 0};
mixChannels(&timg, 1, &gray0, 1, ch, 1);
// try several threshold levels
for( int l = 0; l < N; l++ )
{
// hack: use Canny instead of zero threshold level.
// Canny helps to catch squares with gradient shading
if( l == 0 )
{
// apply Canny. Take the upper threshold from slider
// and set the lower to 0 (which forces edges merging)
Canny(gray0, gray, 0, thresh, 5);
// dilate canny output to remove potential
// holes between edge segments
dilate(gray, gray, Mat(), Point(-1,-1));
}
else
{
// apply threshold if l!=0:
// tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
gray = gray0 >= (l+1)*255/N;
}
// find contours and store them all as a list
findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
vector<Point> approx;
// test each contour
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);
// square contours should have 4 vertices after approximation
// relatively large area (to filter out noisy contours)
// and be convex.
// 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++ )
{
// find the maximum cosine of the angle between joint edges
double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
maxCosine = MAX(maxCosine, cosine);
}
// if cosines of all angles are small
// (all angles are ~90 degree) then write quandrange
// vertices to resultant sequence
if( maxCosine < 0.3 )
squares.push_back(approx);
}
}
}
}
}
// the function draws all the squares in the image
void drawSquares( Mat& image, const vector<vector<Point> >& squares )
{
for( size_t i = 1; i < squares.size(); i++ )
{
const Point* p = &squares[i][0];
int n = (int)squares[i].size();
polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);
}
imshow(wndname, image);
}
int main(int argc, char** argv)
{
if (argc < 2)
{
cout << "Usage: ./program <file>" << endl;
return -1;
}
static const char* names[] = { argv[1], 0 };
help();
namedWindow( wndname, 1 );
vector<vector<Point> > squares;
for( int i = 0; names[i] != 0; i++ )
{
Mat image = imread(names[i], 1);
if( image.empty() )
{
cout << "Couldn't load " << names[i] << endl;
continue;
}
findSquares(image, squares);
drawSquares(image, squares);
imwrite("out.jpg", image);
int c = waitKey();
if( (char)c == 27 )
break;
}
return 0;
}
おそらく、接続されたコンポーネントを見つけてから、Xピクセル未満のコンポーネントを削除し(経験的に決定)、次に水平/垂直線に沿って拡張して、長方形内のギャップを再接続します
ハフ変換は、非常にコストのかかる操作になる可能性があります。
あなたの場合にうまくいく可能性のある代替手段は次のとおりです。
画像クローズ ( http://homepages.inf.ed.ac.uk/rbf/HIPR2/close.htm ) と呼ばれる 2 つの数学的形態操作を実行し、水平線と垂直線 (テストから決定された所定の長さ) の構造要素をそれぞれ使用します。 . これのポイントは、大きな長方形のすべてのギャップを閉じることです。
連結成分分析を実行します。モルフォロジーを効果的に行うと、大きな長方形が 1 つの接続されたコンポーネントとして表示されます。その後、接続されたすべてのコンポーネントを繰り返し処理し、大きな長方形になる可能性が最も高い候補を選択するだけです。
次の 2 つの主な手法に従うことができます。
ベクトルベースの操作: ピクセル アイランドをクラスター (ブロブ、ボロノイ ゾーンなど) にマッピングします。次に、Teh-Chin チェーン近似アルゴリズムなどのヒューリスティックを適用してセグメントを修正し、ベクトル要素 (始点、終点、長さ、向きなど) を刈り込みます。
セット ベースの操作: データをクラスター化します (上記のように)。すべてのクラスターについて、主成分を計算し、有意な固有値が 1 つだけ (楕円に似ている「太い」セグメントを探す場合は 2 つ) を示すクラスターを探して、円またはその他の形状から線を検出します。固有値に関連付けられた固有ベクトルを確認して、ブロブの方向に関する情報を取得し、選択を行います。
どちらの方法も、OpenCV で簡単に調べることができます (前者は、実際、アルゴの「輪郭分析」カテゴリに分類されます)。
以下は、@Tom10 の行に従った単純な形態学的フィルタリング ソリューションです。
matlabでの解決策:
se1 = strel('line',5,180); % linear horizontal structuring element
se2 = strel('line',5,90); % linear vertical structuring element
I = rgb2gray(imread('test.jpg'))>80; % threshold (since i had a grayscale version of the image)
Idil = imdilate(imdilate(I,se1),se2); % dilate contours so that they connect
Idil_area = bwareaopen(Idil,1200); % area filter them to remove the small components
アイデアは、基本的に水平方向の輪郭を接続して大きなコンポーネントを作成し、後でエリアオープニングフィルターでフィルター処理して長方形を取得することです。
結果: