2013-05-14 2 views
11

openCv와 python으로 작업 중이며 Structural Analysis and Shape Descriptors를 다루고 있습니다. 나는이 블로그를 찾았습니다 : http://opencvpython.blogspot.it/2012/06/contours-2-brotherhood.html 그것은 매우 유용합니다. 그리고 나는 경계 사각형을 그리기 위해 흑백 이미지로 시도했습니다. 하지만 이미지에서 나는 예를 들어, 노랑색을 추출하고 경계 사각형을 그리고 싶습니다. 문제는 흑백 이미지가 일정하지 않고 약간의 노이즈가 있고 코드가 전체 모양을 인식하지 못하는 것입니다.OpenCV 2.4 - python 2.7 윤곽선과 경계 사각형 다루기

origianl image

black and white image

final image

그리고 이것은 코드입니다 : 원래 이미지가 상당히 잡음이 때문에

import numpy as np 
import cv2 

im = cv2.imread('shot.bmp') 
hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) 
COLOR_MIN = np.array([20, 80, 80],np.uint8) 
COLOR_MAX = np.array([40, 255, 255],np.uint8) 
frame_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX) 
imgray = frame_threshed 
ret,thresh = cv2.threshold(frame_threshed,127,255,0) 
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 
cnt=contours[0] 
x,y,w,h = cv2.boundingRect(cnt) 
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) 
cv2.imshow("Show",im) 
cv2.waitKey() 
cv2.destroyAllWindows() 
+0

. http://docs.opencv.org/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html – William

+0

원본, 색상, 이미지가 명확하지 않아 어쩌면 노이즈가 발생했을 수 있습니다. – GPPK

+0

예, 명확하지 않습니다. 내 마지막 골은 실시간으로 노란색 객체에 직사각형을 그리기 때문에 웹캠에서 가져온 것입니다. 나는 부식과 확장을 시도 할 것입니다! – Gianfra

답변

30

, 간단한 수정 소음의 일부를 제거하는 것입니다 using cv2.medianBlur() 원본 이미지의 작은 노이즈 영역을 제거합니다. 1 개의 등고선 만 남기십시오. 코드의 처음 몇 줄은 다음과 같이 보일 것이다 : 수동으로 커널 크기를 지정해야하기 때문에

im = cv2.imread('shot.bmp') 
im = cv2.medianBlur(im,5) # 5 is a fairly small kernel size 
hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) 

그러나,이 방법은 가장 강력한 아니며, 코드의 라인 cnt=contours[0]은 가정 관심의 윤곽 윤곽선 목록에있는 전나무입니다. 단 하나의 윤곽선 만있는 경우에만 해당됩니다. 보다 견고한 방법은 사용자가 등고선에 가장 관심이 있다고 가정하는 것입니다.이 경우 약한 노이즈도 보상 할 수 있습니다.

이렇게하려면 줄을 추가

# Find the index of the largest contour 
areas = [cv2.contourArea(c) for c in contours] 
max_index = np.argmax(areas) 
cnt=contours[max_index] 

을 줄 뒤에 :

contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 

을이 코드의 결과 :

이러한 방법의
import numpy as np 
import cv2 

im = cv2.imread('shot.bmp') 
hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) 
COLOR_MIN = np.array([20, 80, 80],np.uint8) 
COLOR_MAX = np.array([40, 255, 255],np.uint8) 
frame_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX) 
imgray = frame_threshed 
ret,thresh = cv2.threshold(frame_threshed,127,255,0) 
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 

# Find the index of the largest contour 
areas = [cv2.contourArea(c) for c in contours] 
max_index = np.argmax(areas) 
cnt=contours[max_index] 

x,y,w,h = cv2.boundingRect(cnt) 
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) 
cv2.imshow("Show",im) 
cv2.waitKey() 
cv2.destroyAllWindows() 

모두가 결과를 제공 올바른 경계 상자 :

Bounding Box Result

N.B. OpenCV의로서는
은 (here 알 수있는 바와 같이) findContours() 방법 3 개 결과를 반환 3.X, 그래서 부가 반환 값처럼 잡힐해야 침식 후 팽창

_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPL‌​E) 
+1

OpenCV를 사용하는 경우 '누수 값이 너무 많습니다.'라는 오류가보고 된 사람을위한 새로운 구문 인 경우 _ _, contours, hierarchy = cv2.findContours (thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 3 및 python 3. ref : https : // stackoverflow를 참조하십시오.com/questions/25504964/opencv-python-valueerror-too-many-values-to-unpack – Puriney

+1

이 문제에서 비롯된 몇 가지 다른 질문이 있으므로 @Puriney의 주석이 정말로 중요하다고 생각합니다. 이 질문은 다음을 포함하도록 편집되어야합니다. – DarkCygnus