Published on

OpenCV 윤곽선 검출

Authors
  • avatar
    Name
    Inhwan Cho
    Twitter
import cv2
import numpy as np
# 이미지 여러 장 출력 함수
def stackImages(scale,imgArray):
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range ( 0, rows):
            for y in range(0, cols):
                if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
                else:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
                if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
        imageBlank = np.zeros((height, width, 3), np.uint8)
        hor = [imageBlank]*rows
        hor_con = [imageBlank]*rows
        for x in range(0, rows):
            hor[x] = np.hstack(imgArray[x])
        ver = np.vstack(hor)
    else:
        for x in range(0, rows):
            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
            else:
                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
        hor= np.hstack(imgArray)
        ver = hor
    return ver

#윤곽선 검출 함수
def getContour(img):
    contours, hierarchy = cv2.findContours(img,mode = cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        # imgContour이미지에 contour를 파란색으로 drawing한다는 의미
        if area > 500 :
            cv2.drawContours(imgContour, cnt, -1, (255,0,0),3) 

img = cv2.imread('Resources/shapes.png')
empty = np.zeros_like(img)
imgContour = img.copy()

imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray, (7,7),1)
imgCanny = cv2.Canny(imgBlur,50,50)
# 보통 contour는 img->gray->blur->canny->contour를 이용하여 검출한다.
getContour(imgCanny)

stackimg = stackImages(0.5,[[img,imgGray, imgBlur],
                            [imgCanny,imgContour,empty]])


cv2.imshow('img', stackimg)

cv2.waitKey(0)
  • 보통 contour는 img->gray->blur->canny->contour를 이용하여 검출한다.
  • 5번째 이미지(imgContour)가 윤곽선이 검출된 이미지
5번째가 윤곽선 검출 이미지

contour를 통하여 bounding box 검출하는 방법입니다

def getContour(img):
    contours, hierarchy = cv2.findContours(img,mode = cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        # imgContour이미지에 contour를 파란색으로 drawing한다는 의미
        if area > 500 :
            cv2.drawContours(imgContour, cnt, -1, (255,0,0),3) 
            param = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * param, True) #근접한 포인트(점)이 있는지 확인
            #print(len(approx)) #3이면 삼각형, 4는 사격형, 그 이상이면 원
            obj_corner = len(approx)

            # object corner를 검출했으면 그걸로 바운딩 박스를 만듭니다.
            x,y,w,h = cv2.boundingRect(approx)

            if obj_corner == 3 :
                object_type = 'triangle'
            elif obj_corner ==4 :
                aspRatio = w/float(h)
                if aspRatio > 0.95 and aspRatio < 1.05:
                    object_type = 'sqare'
                else:
                    object_type = 'rectangle'
            else :
                object_type = 'circle'
            
            #rectangle을 만들고, 텍스트를 붙여서 출력합니다.
            cv2.rectangle(imgContour, (x,y), (x+w, y+h), (0,255,0),2)
            cv2.putText(imgContour, object_type, (x+(w//2)-7, y +(h//2)-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,(0,0,0),2)
        
  • 윤곽선 검출 및 바운딩 박스 생성 이미지(5번째 이미지)
윤곽선 -> 바운딩 박스 생성