[英]How can I check for a contour containing another contour using OpenCV in Python?
Let's say I have the following image and I'm looking to analyse it with OpenCV in Python with Numpy:假设我有以下图像,并且我希望使用 Numpy 在 Python 中使用 OpenCV 对其进行分析:
I mark all the white blocks as contours.我将所有白色块标记为轮廓。 I also mark contours around the red and green dots.
我还在红点和绿点周围标记轮廓。
How do I check which dot is in which white block?如何检查哪个点在哪个白块中?
Here's what I have tried:这是我尝试过的:
import numpy as np
import cv2
img = cv2.imread('crapypimg.bmp')
gray = cv2.imread('crapypimg.bmp',0)
ret, thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
print len(approx)
if len(approx)==4:
print "square"
cv2.drawContours(img,[cnt],0,(0,0,255),2)
elif len(approx) == 9:
print "half-circle"
cv2.drawContours(img,[cnt],0,(255,255,0),3)
elif len(approx) > 15:
print "circle"
cv2.drawContours(img,[cnt],0,(0,255,255),3)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
img = cv2.imread('OFLCp.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)[1] # ensure binary
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
hierarchy is the answer to your question.If you will check hierarchy, it will look like this:层次结构是您问题的答案。如果您检查层次结构,它将如下所示:
array([[[-1, -1, 1, -1],
[ 3, -1, 2, 0],
[-1, -1, -1, 1],
[ 4, 1, -1, 0],
[ 6, 3, 5, 0],
[-1, -1, -1, 4],
[ 7, 4, -1, 0],
[ 9, 6, 8, 0],
[-1, -1, -1, 7],
[10, 7, -1, 0],
[12, 9, 11, 0],
[-1, -1, -1, 10],
[-1, 10, -1, 0]]], dtype=int32)
where each row contains hierarchy information of the contour at that index.其中每一行包含该索引处轮廓的层次结构信息。
row = [next_contour_index, previous_contour_index, first_child_contour_index, parent_contour_index] row = [next_contour_index, previous_contour_index, first_child_contour_index, parent_contour_index]
so, 0 here is index of outermost square.所以,这里的 0 是最外层方块的索引。 contour at index 2 (circle) has parent as 1 (square).
索引 2(圆形)处的轮廓的父级为 1(方形)。 Plotting one pair of child(red), parent (yellow).
绘制一对孩子(红色),父母(黄色)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.