A program using pyramid scaling, Canny, contours and contour simplification to find squares in the input image.
#include <iostream>
using namespace std;
int thresh = 50, N = 11;
const char* wndname = "Square Detection Demo";
{
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);
}
static void findSquares( const UMat& image, vector<vector<Point> >& squares )
{
squares.clear();
UMat pyr, timg, gray0(image.size(),
CV_8U), gray;
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;
for( int c = 0; c < 3; c++ )
{
int ch[] = {c, 0};
for( int l = 0; l < N; l++ )
{
if( l == 0 )
{
Canny(gray0, gray, 0, thresh, 5);
}
else
{
}
vector<Point> approx;
for( size_t i = 0; i < contours.size(); i++ )
{
if( approx.size() == 4 &&
{
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);
}
}
}
}
}
static void drawSquares( UMat& _image, const vector<vector<Point> >& squares )
{
for( size_t i = 0; i < squares.size(); i++ )
{
const Point* p = &squares[i][0];
int n = (int)squares[i].
size();
}
}
static UMat drawSquaresBoth( const UMat& image,
const vector<vector<Point> >& sqs)
{
UMat imgToShow(
Size(image.cols, image.rows), image.type());
image.copyTo(imgToShow);
drawSquares(imgToShow, sqs);
return imgToShow;
}
int main(int argc, char** argv)
{
const char* keys =
"{ i input | ../data/pic1.png | specify input image }"
"{ o output | squares_output.jpg | specify output save path}"
"{ h help | | print help message }"
"{ m cpu_mode | | run without OpenCL }";
CommandLineParser cmd(argc, argv, keys);
if(cmd.has("help"))
{
cout << "Usage : " << argv[0] << " [options]" << endl;
cout << "Available options:" << endl;
cmd.printMessage();
return EXIT_SUCCESS;
}
if (cmd.has("cpu_mode"))
{
cout << "OpenCL was disabled" << endl;
}
string outfile = cmd.get<string>("o");
int iterations = 10;
vector<vector<Point> > squares;
UMat image;
if( image.empty() )
{
cout << "Couldn't load " << inputName << endl;
cmd.printMessage();
return EXIT_FAILURE;
}
int j = iterations;
cout << "warming up ..." << endl;
findSquares(image, squares);
do
{
findSquares(image, squares);
cout << "run loop: " << j << endl;
}
while(--j);
cout <<
"average time: " << 1000.0f * (double)t_cpp /
getTickFrequency() / iterations <<
"ms" << endl;
UMat result = drawSquaresBoth(image, squares);
return EXIT_SUCCESS;
}
void copyTo(OutputArray m) const
Copies the matrix to another one.
void mixChannels(const Mat *src, size_t nsrcs, Mat *dst, size_t ndsts, const int *fromTo, size_t npairs)
Copies specified channels from input arrays to the specified channels of output arrays.
Point2i Point
Definition: types.hpp:198
Size2i Size
Definition: types.hpp:359
Scalar_< double > Scalar
Definition: types.hpp:685
@ ACCESS_WRITE
Definition: mat.hpp:64
#define CV_8U
Definition: interface.h:73
int64_t int64
Definition: interface.h:61
void setUseOpenCL(bool flag)
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
double getTickFrequency()
Returns the number of ticks per second.
int64 getTickCount()
Returns the number of ticks.
#define MAX(a, b)
Definition: cvdef.h:493
Quat< S > sqrt(const Quat< S > &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT)
@ WINDOW_AUTOSIZE
the user cannot resize the window, the size is constrainted by the image displayed.
Definition: highgui.hpp:188
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
int waitKey(int delay=0)
Waits for a pressed key.
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
@ IMREAD_COLOR
If set, always convert image to the 3 channel BGR color image.
Definition: imgcodecs.hpp:72
CV_EXPORTS_W bool imwrite(const String &filename, InputArray img, const std::vector< int > ¶ms=std::vector< int >())
Saves an image to a specified file.
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR)
Loads an image from a file.
void polylines(InputOutputArray img, InputArrayOfArrays pts, bool isClosed, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws several polygonal curves.
@ LINE_AA
antialiased line
Definition: imgproc.hpp:816
void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false)
Finds edges in an image using the Canny algorithm .
void dilate(InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar &borderValue=morphologyDefaultBorderValue())
Dilates an image by using a specific structuring element.
void pyrUp(InputArray src, OutputArray dst, const Size &dstsize=Size(), int borderType=BORDER_DEFAULT)
Upsamples an image and then blurs it.
void pyrDown(InputArray src, OutputArray dst, const Size &dstsize=Size(), int borderType=BORDER_DEFAULT)
Blurs an image and downsamples it.
double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)
Applies a fixed-level threshold to each array element.
@ THRESH_BINARY
Definition: imgproc.hpp:321
void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed)
Approximates a polygonal curve(s) with the specified precision.
double contourArea(InputArray contour, bool oriented=false)
Calculates a contour area.
bool isContourConvex(InputArray contour)
Tests a contour convexity.
double arcLength(InputArray curve, bool closed)
Calculates a contour perimeter or a curve length.
void findContours(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())
Finds contours in a binary image.
@ CHAIN_APPROX_SIMPLE
Definition: imgproc.hpp:442
@ RETR_LIST
Definition: imgproc.hpp:423
GOpaque< Size > size(const GMat &src)
Gets dimensions from Mat.
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:52