问题描述
我目前正在运行精明的边缘检测并检测两个方形对象。我检测边缘并使用
列出坐标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 的数量,它也不会工作,因为该系统可能检测到不同的数量的正方形。我也尝试使用 blob 检测,但这似乎需要我填写检测到的方块,当我已经有了坐标时,这似乎是在浪费时间。
编辑
Here is an example image with the edge detections in
解决方法
我正在使用 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);