OpenCV  5.0.0alpha-pre
Open Source Computer Vision
Loading...
Searching...
No Matches
samples/python/snippets/squares.py

An example using approxPolyDP function in python.

1#!/usr/bin/env python
2
3'''
4Simple "Square Detector" program.
5
6Loads several images sequentially and tries to find squares in each image.
7'''
8
9import numpy as np
10import cv2 as cv
11
12
13def angle_cos(p0, p1, p2):
14 d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
15 return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
16
17def find_squares(img):
18 img = cv.GaussianBlur(img, (5, 5), 0)
19 squares = []
20 for gray in cv.split(img):
21 for thrs in range(0, 255, 26):
22 if thrs == 0:
23 bin = cv.Canny(gray, 0, 50, apertureSize=5)
24 bin = cv.dilate(bin, None)
25 else:
26 _retval, bin = cv.threshold(gray, thrs, 255, cv.THRESH_BINARY)
27 contours, _hierarchy = cv.findContours(bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
28 for cnt in contours:
29 cnt_len = cv.arcLength(cnt, True)
30 cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
31 if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
32 cnt = cnt.reshape(-1, 2)
33 max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)])
34 if max_cos < 0.1:
35 squares.append(cnt)
36 return squares
37
38def main():
39 from glob import glob
40 for fn in glob('../data/pic*.png'):
41 img = cv.imread(fn)
42 squares = find_squares(img)
43 cv.drawContours( img, squares, -1, (0, 255, 0), 3 )
44 cv.imshow('squares', img)
45 ch = cv.waitKey()
46 if ch == 27:
47 break
48
49 print('Done')
50
51
52if __name__ == '__main__':
53 print(__doc__)
54 main()
void split(const Mat &src, Mat *mvbegin)
Divides a multi-channel array into several single-channel arrays.
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 destroyAllWindows()
Destroys all of the HighGUI windows.
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
void drawContours(InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar &color, int thickness=1, int lineType=LINE_8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point())
Draws contours outlines or filled contours.
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 GaussianBlur(InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY=0, int borderType=BORDER_DEFAULT, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT)
Blurs an image using a Gaussian filter.
double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)
Applies a fixed-level threshold to each array element.
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.
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3