python - 使用opencv2 python在图像中矩形和正方形之间的区分

标签 python opencv image-processing cv2 shape-recognition

我正在学习如何识别所提供图像中的形状。我能够通过出现在几何体上的边缘数量来识别形状。但是现在我想知道有什么方法可以区分图像中的正方形和矩形吗?
这是我的代码。目前,我只是在为几何图形绘制轮廓。

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)

This is sample image

最佳答案

如果宽度和高度相同,则为正方形。否则它是一个矩形。

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)进行区分。

enter image description here

关于python - 使用opencv2 python在图像中矩形和正方形之间的区分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257299/

相关文章:

javascript - 从图像中提取 RGB channel

android - 使用 App Engine Python 的 C2DM 返回 401 错误

python - 从列表列表中获取 (x,y) 坐标

c++ - opencv 相机校准 object_points 方向

numpy - 使用来自 numpy 数组的 opencv 的灰度图像失败

Python - 如何在窗口中显示透明图像?

android - 如何将android触摸坐标转换为OpenCV图像坐标?

python - cx_Oracle : DLL load failed

python - 如果打开现有的 Chrome 窗口,使用默认选项的 Selenium Webdriver 永远不会返回

opencv - 我可以使用已知对象大小而不是平面来估计相机姿势/外部参数吗?