我正在学习如何识别所提供图像中的形状。我能够通过出现在几何体上的边缘数量来识别形状。但是现在我想知道有什么方法可以区分图像中的正方形和矩形吗?
这是我的代码。目前,我只是在为几何图形绘制轮廓。
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)
最佳答案
如果宽度和高度相同,则为正方形。否则它是一个矩形。
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)
此更改仅检测正方形和矩形。在for循环中进行必要的更改以检测圆。您可以使用
len(approx)
进行区分。关于python - 使用opencv2 python在图像中矩形和正方形之间的区分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257299/