首页 > 解决方案 > 在python中从opencv中分离多个canny边缘检测的坐标

问题描述

我目前正在运行精明的边缘检测,并且正在检测两个方形物体。我检测边缘并使用列出坐标

colourMap = cv2.imread('Colour_Map_Generated2.jpg',0)
edges = cv2.Canny(colourMap,10,20) 

cv2.imwrite('/home/pi/Desktop/edgesDetected.jpg',edges)

indices = np.where(edges != [0])
coordinates = zip(indices[0], indices[1])

但是这种方法将所有坐标放在一个列表中,我如何将每个正方形的坐标放在一个单独的数组中?

到目前为止,我已经尝试确定 2 个 ROI,但是在我尝试时检测到整个图像因此是不成功的,此外,如果我要硬设置 ROI 的数量,它也将不起作用,因为该系统可能检测到不同数量的正方形。我也尝试使用斑点检测,但这似乎需要我填写检测到的方块,当我已经有了坐标时,这似乎是在浪费时间。

编辑

这是带有边缘检测的示例图像

标签: pythonopencvcanny-operator

解决方案


我正在使用 findContours 来获取每个矩形的点。由于 findContours 将给出空心形状的内部和外部轮廓,因此我们必须通过检查相似的周长来删除重复项。

在此处输入图像描述

import cv2
import numpy as np

# load image
img = cv2.imread("rectangles.png");

# make a mask
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
mask = cv2.inRange(gray, 100, 255);

# get contours # OpenCV 3.4, if you're using OpenCV 2 or 4, it returns (contours, _)
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);
print(len(contours));

# remove contours with very similar perimeters (we get back inner and outer contours)
cutoff_percent = 0.05;
no_dupes = [];
for con in contours:
    perim = cv2.arcLength(con, closed = True);
    # check for duplicate
    dupe_flag = False;
    for dupe in no_dupes:
        dupe_perim = cv2.arcLength(dupe, closed = True);
        if abs(dupe_perim - perim) < cutoff_percent * perim:
            dupe_flag = True;
            break;

    # add to list
    if not dupe_flag:
        no_dupes.append(con);
print(len(no_dupes));

# draw each one sequentially
blank = np.zeros_like(img);
cv2.imwrite("blank.png", blank);
for a in range(len(no_dupes)):
    cv2.drawContours(blank, [no_dupes[a]], -1, (200, 200, 0), 1);
    cv2.imshow("blank", blank);
    cv2.waitKey(0);

# show
cv2.imshow("Image", img);
cv2.waitKey(0);

推荐阅读