250x250
Link
나의 GitHub Contribution 그래프
Loading data ...
Notice
Recent Posts
Recent Comments
관리 메뉴

Data Science LAB

[Python] OpenCV 기초 14 - 이미지 검출 (2) (윤곽선) 본문

🖥️ Computer Vision/Opencv

[Python] OpenCV 기초 14 - 이미지 검출 (2) (윤곽선)

ㅅ ㅜ ㅔ ㅇ 2022. 8. 15. 21:44
728x90

1. 윤곽선 검출 (Contour) : 경계선을 연결한 선

rat, otsu = cv.threshold([이미지], -1, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
cv2.findCountours(otsu, [윤곽선 찾기 모드], cv2.CHAIN_APPORX_NONE)
import cv2
img = cv2.imread('img.png')
target_img = img.copy()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rat, otsu = cv2.threshold(gray, -1, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

contours, hierachy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # 윤곽선 검출
# 윤곽선 정보, 윤곽선 구조 
# 이미지, 윤곽선을 찾는 모드(mode), 윤곽선을 찾을때 사용하는 근사치 방법(method) : cv2.CHAIN_APPROX_SIMPLE, cv2.CHAIN_APPROX_NONE

COLOR = (0,200,0) # 녹색
cv2.drawContours(target_img, contours, -1, COLOR, 2) #윤곽선 그리기
# 대상 이미지, 윤곽선 정보, 인데스(-1이면 전체), 색깔, 두께

cv2.imshow('img',img)
cv2.imshow('gray',gray)
cv2.imshow('otsu',otsu)
cv2.imshow('contour',target_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

 

윤곽선 찾기 모드 

1. cv2.RETR_EXTERNAL : 가장 외곽의 윤곽선만 찾음
2. cv2.RETR_LIST : 모든 윤곽선 찾음(계층 정보 없음)
3. cv2.RETR_TREE : 모든 윤곽선 찾으(계층 정보를 트리 구조로 생성)

 

 

2. 경계 사각형 찾기 (boundingRect())

import cv2
img = cv2.imread('jpg.png')
target_img = img.copy()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rat, otsu = cv2.threshold(gray, -1, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

contours, hierachy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # 윤곽선 검출



COLOR = (0,200,0) # 녹색

for cnt in contours:
    x,y , width, height = cv2.boundingRect(cnt)
    cv2.rectangle(target_img, (x,y), (x+width, y+height), COLOR, 2) # 사각형 그림

cv2.imshow('img',img)
cv2.imshow('gray',gray)
cv2.imshow('otsu',otsu)
cv2.imshow('contour',target_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

 

 

3. 사각형 면적 구하기 (contourArea())

import cv2
img = cv2.imread('card.png')
target_img = img.copy()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rat, otsu = cv2.threshold(gray, -1, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

contours, hierachy = cv2.findContours(otsu, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # 윤곽선 검출



COLOR = (0,200,0) # 녹색

for cnt in contours:
    if cv2.contourArea(cnt) > 25000:
        x,y , width, height = cv2.boundingRect(cnt)
        cv2.rectangle(target_img, (x,y), (x+width, y+height), COLOR, 2) # 사각형 그림
        

cv2.imshow('img',img)
cv2.imshow('gray',gray)
cv2.imshow('otsu',otsu)
cv2.imshow('contour',target_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
728x90
Comments