๋ณธ ๊ธ€์€ 2020-2ํ•™๊ธฐ โ€œ์ปดํ“จํ„ฐ ๋น„์ „โ€ ์ˆ˜์—…์„ ๋“ฃ๊ณ , ์Šค์Šค๋กœ ํ•™์Šตํ•˜๋ฉด์„œ ๊ฐœ์ธ์ ์ธ ์šฉ๋„๋กœ ์ •๋ฆฌํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ง€์ ์€ ์–ธ์ œ๋‚˜ ํ™˜์˜์ž…๋‹ˆ๋‹ค :)

2 minute read

๋ณธ ๊ธ€์€ 2020-2ํ•™๊ธฐ โ€œ์ปดํ“จํ„ฐ ๋น„์ „โ€ ์ˆ˜์—…์„ ๋“ฃ๊ณ , ์Šค์Šค๋กœ ํ•™์Šตํ•˜๋ฉด์„œ ๊ฐœ์ธ์ ์ธ ์šฉ๋„๋กœ ์ •๋ฆฌํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ง€์ ์€ ์–ธ์ œ๋‚˜ ํ™˜์˜์ž…๋‹ˆ๋‹ค :)



์ˆ˜์—… ๋‚ด์šฉ ์ค‘, Convolution filter๋ฅผ ์ด์šฉํ•ด ์ด๋ฏธ์ง€์˜ Edge๋ฅผ ์ถ”์ถœํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ Gradient filter๊ฐ€ ์†Œ๊ฐœ๋˜์—ˆ๋‹ค.

์‹ค์ œ๋กœ ์–ด๋–ค ๊ฒฐ๊ณผ๊ฐ€ ์ƒ๊ธฐ๋Š”์ง€ ํฅ๋ฏธ๊ฐ€ ์ƒ๊ฒจ ์ง์ ‘ ์ฝ”๋“œ๋กœ ํ™•์ธํ•ด๋ณด์ž.


Gradient filter๋Š” openCV์˜ ํ•จ์ˆ˜๋“ค์„ ์ด์šฉํ•ด ์ •๋ง ์‰ฝ๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค!

๋จผ์ € ์ „์ฒด ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

import cv2

IMG_PATH = "origin.png"

if __name__ == "__main__":
  # load image
  img = cv2.imread(IMG_PATH)

  # make image gray
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  # take gradient
  ## Gaussian blurring
  blurred = cv2.GaussianBlur(img, (3, 3), 0)

  ## sobel filter
  sobelX = cv2.Sobel(blurred, cv2.CV_8U, 1, 0, ksize=3)
  sobelY = cv2.Sobel(blurred, cv2.CV_8U, 0, 1, ksize=3)

  ## merge two gradients
  gradient = sobelX + sobelY

  cv2.imshow("Gradient Image", gradient)
  cv2.waitKey()
  # cv2.imwrite("Gradient Image", gradient)

์ฝ”๋“œ์˜ ๋กœ์ง์„ ํ•˜๋‚˜์”ฉ ์‚ดํŽด๋ณด์ž.


์ด๋ฏธ์ง€์˜ Edge๋งŒ ์‚ดํŽด๋ณผ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— RGB ์ด๋ฏธ์ง€๋ฅผ gray ์ด๋ฏธ์ง€๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.

  # make image gray
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


๋จผ์ € ์ž…๋ ฅ๋œ ์ด๋ฏธ์ง€์— Gaussian ํ•„ํ„ฐ๋ฅผ ์ ์šฉํ•ด blurringํ•œ๋‹ค. Gaussian ํ•„ํ„ฐ๋Š” ์ ์š”ํ•˜๋ฉด Noise๋ฅผ ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ์–ด, ๋” niceํ•œ ๊ฒฐ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.

  ## Gaussian blurring
  blurred = cv2.GaussianBlur(img, (3, 3), 0)


์ด์ œ ์ด๋ฏธ์ง€์— Gradient๋ฅผ ์ ์šฉํ•˜๋Š” ๋ถ€๋ถ„์ด๋‹ค. Gradient filter๋ฅผ Sobel filter๋ผ๊ณ ๋„ ํ•˜๋Š”๋ฐ, openCV์˜ cv2.Sobel() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค!

  ## sobel filter
  sobelX = cv2.Sobel(blurred, cv2.CV_8U, 1, 0, ksize=3)
  sobelY = cv2.Sobel(blurred, cv2.CV_8U, 0, 1, ksize=3)

sobelX๋Š” ์ˆ˜ํ‰ ์„ฑ๋ถ„์„ ์ œ๊ฑฐํ•œ ์ด๋ฏธ์ง€๋กœ, ์ˆ˜์ง Edge๋ฅผ ๊ฒ€์ถœํ•œ๋‹ค. ๋ฐ˜๋Œ€๋กœ sobelY๋Š” ์ˆ˜์ง ์„ฑ๋ถ„์„ ์ œ๊ฑฐํ•œ ์ด๋ฏธ์ง€๋กœ, ์ˆ˜ํ‰ Edge๋ฅผ ๊ฒ€์ถœํ•œ๋‹ค.


์ด์ œ ์ˆ˜์ง/์ˆ˜ํ‰ Edge๋ฅผ ๊ฒ€์ถœํ•œ ๊ฒƒ์„ ํ•ฉ์ณ์ฃผ๋ฉด ๋œ๋‹ค.

  ## merge two gradients
  gradient = sobelX + sobelY

์ถœ๋ ฅ๋œ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ์•Œ ์ˆ˜ ์žˆ๋“ฏ์ด cv2.Sobel()๊ฐ™์€ openCV์˜ ํ•จ์ˆ˜๋“ค์„ ์ž˜ ์ด์šฉํ•˜๋ฉด ์ด๋ฏธ์ง€์˜ Edge๋ฅผ ์‰ฝ๊ฒŒ ๊ฒ€์ถœํ•  ์ˆ˜ ์žˆ๋‹ค.

์ˆ˜์—… PPT์— ์žˆ๋Š” ์‚ฌ์ง„์€ ๊ฒฐ๊ณผ๊ฐ€ ํšŒ์ƒ‰ ๋ฐฐ๊ฒฝ์ด๋˜๋ฐ, ๋ณธ์ธ์˜ ๊ฒฐ๊ณผ๋Š” ๊ฒ€์€ ๋ฐฐ๊ฒฝ์œผ๋กœ ์ถœ๋ ฅ์ด ๋œ๋‹ค. ์•„๋งˆ ์ „์ฒ˜๋ฆฌ ๋ฐฉ์‹์ด ์กฐ๊ธˆ ๋‹ค๋ฅธ ๊ฒƒ ๊ฐ™๋‹ค!


์‹ฌ์‹ฌํ•ด์„œ ๋ณธ์ธ ๋กœ๊ณ ์—๋„ ์ ์šฉํ•ด๋ดค๋‹ค ใ…Žใ…Ž