霍夫很棒,但可能有点贵
这可能有效:
- 使用 Threshold 或 Canny 找到图像的边缘。
-然后cvFindContours识别轮廓,然后尝试检测矩形。
检查 opencv 发行版中的 squares.c 示例。它基本上检查轮廓的多边形近似是否有 4 个点,并且这些点之间的平均角度是否接近 90 度。
这是 squares.py 示例中的代码片段
(是相同的,但是在 python 中:P)。
..some pre-processing
cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
# find contours and store them all as a list
count, contours = cvFindContours(gray, storage)
if not contours:
continue
# test each contour
for contour in contours.hrange():
# approximate contour with accuracy proportional
# to the contour perimeter
result = cvApproxPoly( contour, sizeof(CvContour), storage,
CV_POLY_APPROX_DP, cvContourPerimeter(contour)*0.02, 0 );
res_arr = result.asarray(CvPoint)
# 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( result.total == 4 and
abs(cvContourArea(result)) > 1000 and
cvCheckContourConvexity(result) ):
s = 0;
for i in range(4):
# find minimum angle between joint
# edges (maximum of cosine)
t = abs(angle( res_arr[i], res_arr[i-2], res_arr[i-1]))
if s<t:
s=t
# if cosines of all angles are small
# (all angles are ~90 degree) then write quandrange
# vertices to resultant sequence
if( s < 0.3 ):
for i in range(4):
squares.append( res_arr[i] )
-使用 MinAreaRect2(查找给定 2D 点集的最小面积的外接矩形),获取矩形的边界框。使用边界框点可以轻松计算角度。
您还可以在 opencv 目录中的samples/c/ 下找到C 版本的squares.c。