๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ‘จ๐Ÿผ‍๐Ÿ’ป๊ฐœ๋ฐœ/OpenCV

OpenCV - ์บก์ฑ  ๋ฌธ์ž ๊ฒ€์ถœํ•˜๊ธฐ

by Janger 2022. 5. 18.
728x90
๋ฐ˜์‘ํ˜•
import cv2
import numpy as numpy
import matplotlib.pyplot as plt

img = cv2.imread('./characters.PNG')
img = cv2.blur(img, (10, 10), anchor=(-1, -1), borderType=cv2.BORDER_DEFAULT) # ๋ธ”๋Ÿฌ์ฒ˜๋ฆฌ(๋–จ์–ด์ง„ ์กฐ๊ฐ์„ ๋ถ™์ด๊ธฐ)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # ํšŒ์ƒ‰ ์ „ํ™˜

img_gray = 255 - img_gray # ์ด๋ฏธ์ง€ ๋ฐ˜์ „

res, thr = cv2.threshold(img_gray, 90, 255, cv2.THRESH_BINARY) # ์ด์ง„ํ™”
cv2.imshow('gray', thr)


contours, hierachy = cv2.findContours(thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # ์œค๊ณฝ์„  ์ถ”์ถœ

# ์œค๊ณฝ์„  ๊ทธ๋ฆฌ๊ธฐ
for cnt in contours[0:]:
    cv2.drawContours(img, [cnt], -1, (255, 255, 0), 2)


temp_img = img

# https://answers.opencv.org/question/179510/how-can-i-sort-the-contours-from-left-to-right-and-top-to-bottom/
contours = sorted( contours, key=lambda ctr: cv2.boundingRect(ctr)[0]) # X์˜ ์œ„์น˜๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ด๋ฏธ์ง€ ์ˆœ์„œ ์ •๋ ฌ



for cnt in contours[:]:
    x, y, w, h = cv2.boundingRect(cnt)

    if (h, w) > (10, 10):
        cv2.rectangle(img, (x,y), (x+w, y+h), (0, 0, 255), 3)

        # ์‚ฌ์ด์ฆˆ๋งŒํผ ์ถ”์ถœ
        cropped = temp_img[y:y+h, x:x+w]
        
        # ์‚ฌ์ด์ฆˆ ๋‘๋ฐฐ
        cropped = cv2.pyrUp(cropped, dstsize=(w*2, h*2), borderType=cv2.BORDER_DEFAULT)
        
                
        cv2.imshow('cropped', cropped)
        cv2.waitKey(0)



cv2.imshow('frame', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

 

 

๊ฒฐ๊ณผ: 

 

์ฐธ์กฐ: 

https://076923.github.io/posts/Python-opencv-21/

 

Python OpenCV ๊ฐ•์ขŒ : ์ œ 21๊ฐ• - ์œค๊ณฝ์„  ๊ฒ€์ถœ

์œค๊ณฝ์„ (Contour)

076923.github.io

 

728x90
๋ฐ˜์‘ํ˜•