2014-04-04 4 views
9

필자는 손으로 그린 ​​그림의 모양을 인식하기 위해 Python 스크립트를 구현했습니다. 그러나 스크립트는 필요한 것보다 많은 모양을 인식합니다.Python에서 findContours에 대한 계층 구조 사용

: 여기

이 예제 사진입니다 :

enter image description here

이 스크립트의 출력 : 다음 내가 쓴 코드의

enter image description here

부분이다

def create_graph(vertex, color): 
    for g in range(0, len(vertex)-1): 
     for y in range(0, len(vertex[0][0])-1): 
      cv2.circle(newimg, (vertex[g][0][y], vertex[g][0][y+1]), 3, (255,255,255), -1) 
      cv2.line(newimg, (vertex[g][0][y], vertex[g][0][y+1]), (vertex[g+1][0][y], vertex[g+1][0][y+1]), color, 2) 
    cv2.line(newimg, (vertex[len(vertex)-1][0][0], vertex[len(vertex)-1][0][1]), (vertex[0][0][0], vertex[0][0][1]), color, 2) 


img = cv2.imread('star.jpg') 
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

#Remove of noise, if any 
kernel = np.ones((2, 2),np.uint8) 
erosion = cv2.erode(gray, kernel, iterations = 1) 

#Create a new image of the same size of the starting image 
height, width = gray.shape 
newimg = np.zeros((height, width, 3), np.uint8) 

#Canny edge detector 
thresh = 175 
edges = cv2.Canny(erosion, thresh, thresh*2) 

contours,hierarchy = cv2.findContours(edges, cv2.cv.CV_RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) 
for b,cnt in enumerate(contours): 
    if hierarchy[0,b,3] == -1: #<-the mistake might be here 
     approx = cv2.approxPolyDP(cnt,0.015*cv2.arcLength(cnt,True), True) 
     clr = (255, 0, 0) 
     create_graph(approx, clr) #function for drawing the found contours in the new img 
cv2.imwrite('starg.jpg', newimg) 

나는 모든 코드는 쓸모가 없기 때문에. 나는 윤곽을 찾기 위해 계층 구조의 사용을 착각하고 있다고 생각한다. 필자는 그러한 파이썬 전문가가 아니며 컨투어에서 계층의 사용을 잘 이해하지 못했습니다. 아무도 제안이 있습니까?

답변

3

외부 윤곽 만 검색되도록 findContours의 플래그를 변경하십시오. 다음 예제와 같이 RETR_EXTERNAL 플래그를 사용하십시오.

contours,hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 

이렇게하면 문제가 해결됩니다.