공부/Python
[Opencv] connectedComponents & connectedComponentsWithStats
잠수함토끼
2019. 2. 18. 20:46
connectedComponents & connectedComponentsWithStats
0 0 0 0 0 0
1 0 0 0 1 0
1 0 0 0 1 0
1 0 0 0 1 0
1 1 0 0 0 0
위와 같이 어떤 image에 저와 같은 배열을 갖는 이미지가 있었다.
우리가 cv2.connectedComponents(image) 를 하면 연결된 components의 개수를 반환하고 Labeling을 해준다.
0 0 0 0 0 0
1 0 0 0 2 0
1 0 0 0 2 0
1 0 0 0 2 0
1 1 0 0 0 0
그럼 우리는 이것들을 분리해서 처리할 수 있다.
또한 cv2.connectedComponentsWithStats() 는 중심 좌표 및 범위를 알려주기 때문에
대상(component)를 특정화 시킬수 있다.
import cv2
import numpy as np
img = cv2.imread('imagePath') # color image load
gray = cv2.cvtColor(img, cv2.Color_bgr2gray) # gray 변환
ret, labels, stats, centriods = cv2.connectedComponentsWithStats(gray)
img1 = np.zeros(img.shape, dtype=img.dtype)
for i in range(1, ret):
r = np.random.randint(256)
g = np.random.randint(256)
b = np.random.randint(256)
img1[labels==i] = [b, g, r]
x, y, width, height = stats[i]
cv2.rectangle(img1, (x, y), (x+width, y+height), (0,0,255), 2)
cx, cy = centriods[i]
cv2.circle(img1, (int(cx), int(cy)), 5, (255,0,0), -1)
cv2.imshow('components', img1)
cv2.waitkey()
cv2.destroyAllwindows()
이렇게 하면 중점과 범위를 표기할 수 있다.