在python中从opencv分离多个canny边缘检测的坐标

2024-06-02 22:51:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在运行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的数量,它也不会工作,因为这个系统可能检测到不同数量的正方形。我还尝试使用斑点检测,但这似乎需要我填写检测到的方块,这似乎是浪费时间,因为我已经有了坐标

编辑

Here is an example image with the edge detections in


Tags: 对象map数量cv2边缘jpg方形colour
1条回答
网友
1楼 · 发布于 2024-06-02 22:51:36

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

enter image description here

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);

相关问题 更多 >