Reputation: 107
Let's say I have the following image and I'm looking to analyse it with OpenCV in Python with Numpy:
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()
Upvotes: 2
Views: 4302
Reputation: 78
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]
so, 0 here is index of outermost square.
contour at index 2 (circle) has parent as 1 (square). Plotting one pair of child(red), parent (yellow).
Upvotes: 1