我正在学习如何识别所提供图像中的形状。我能够通过几何体上存在的边数来识别形状。但是现在我想知道有没有办法区分图像中的正方形和矩形? 这是我的代码。目前,我只是在绘制几何图形的轮廓。
import cv2
raw_image = cv2.imread('test1.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)
bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)
edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)
_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contour_list = []
for contour in contours:
approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
area = cv2.contourArea(contour)
if ((len(approx) >= 3)):
contour_list.append(contour)
cv2.drawContours(raw_image, contour_list, -1, (0,0,0), 2)
cv2.imshow('Objects Detected',raw_image)
cv2.waitKey(0)
答案 0 :(得分:2)
It is a square if its width and height are same. Otherwise its a rectangle.
for contour in contours:
approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
area = cv2.contourArea(contour)
if ((len(approx) == 4)):
(x, y, w, h) = cv2.boundingRect(approx)
if ((float(w)/h)==1):
cv2.putText(raw_image, "square", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, 0, 2)
else:
cv2.putText(raw_image, "rectangle", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, 0, 2)
contour_list.append(contour)
This change only detects squares and rectangles. Make necessary changes in the for loop to detect circles. You can work with len(approx)
to make that distinction.
答案 1 :(得分:1)
我有另一种方式:
查找所有已连接的组件。
在原始图像中找到要素点,因为在这种情况下我们有简单的几何体而不是复杂的对象,您可以使用角点作为特征点,使用Harris角算法。
将这些要素点分组在相同的连接组件上。
使用所有连接组件上这些要素点之间的关系(距离/角度),因此您可以对这些几何形状进行分类。
答案 2 :(得分:1)
The difference between a rectangle and a square is that a square has 4 equal sides making it a special rectangle. I learned this in kindergarden.
There are countless ways of identifying a square.
Its circumference always equals sqrt(area) hence its circularity is always 0.0625
The distance between all corners is either a or a * sqrt(2)
The centroid has the same distance a / 2 to all 4 sides
...
You name it.
答案 3 :(得分:0)
我在评论中读到形状可能会旋转。在那种情况下,cv2.boundingRect()不会给出正确的结果,因为此函数始终会给出一个直立的矩形。一般而言,要检测矩形(是否旋转),应尝试cv2.minAreaRect(),该函数将返回一个矩形,该矩形将根据轮廓旋转,并具有覆盖轮廓的最小面积。然后,您可以检查其长宽比,以查看它是正方形还是矩形。