줘이리의 인생적기

CV - opencv(Python) Blur, GaussianBlur, MedianBlur 본문

공부/Computer Vision(py)

CV - opencv(Python) Blur, GaussianBlur, MedianBlur

줘이리 2020. 7. 17. 08:00
728x90

Blur, GaussianBlur, MedianBlur에 대해 알아보겠습니다.

 

 

그전에, 영상 평활화(Image Smoothing, Image Blurring)를 알아보겠습니다.

영상 평활화는 영상을 부드럽게 표현하거나 잡음을 제거하기 위해 사용되며, 평균값 필터링(mean filtering) 및 중간값 필터링(median filtering) 연산을 통해 수행되어집니다.

 

평균값 필터링(mean filtering)

-모든 계수가 양수, 전체 합이 1인 마스크

-weight의 형태에 따라 Gaussian filtering이라고도 불림.

 

중간값 필터링(median filtering)

-Nonlinear filtering

-중앙의 픽셀 값이 필터 영역 내 모든 픽셀 값의 중앙값으로 대체됨.

 

 

1번 imageBlur, GaussianBlur

 

2번 MedianBlur

 

 

코드 원형 설명

#Blur
def imageBlur(image, ksize):
    size = ((ksize+1) * 2 - 1, (ksize+1) * 2 - 1)
    return cv2.blur(image, size)

#GaussianBlur
def imageGaussianBlur(image, ksize, sigmaX, sigmaY):
    size = ((ksize+1) * 2 - 1, (ksize+1) * 2 - 1)
    return cv2.GaussianBlur(image, ksize=size, sigmaX=sigmaX, sigmaY=sigmaY)

#Medianblur
def imageMedianBlur(image, size):
    ksize = (size+1) * 2 - 1
    return cv2.medianBlur(image, ksize)

 

1번 코드 설명

더보기
# -*- coding: utf-8 -*-
from OpenCV_Functions import *

def nothing(x):
    pass

#이미지 설정
imagePath = "<이미지 경로>"
image = imageRead(imagePath) 
backup = imageCopy(image)

#창 설정
cv2.namedWindow('Mean and gaussian', cv2.WINDOW_GUI_EXPANDED)

#트랙바 설정
cv2.createTrackbar('BlurSize', 'Mean and gaussian', 0, 10, nothing)
cv2.createTrackbar('sigmaX', 'Mean and gaussian', 0, 50, nothing)
cv2.createTrackbar('sigmaY', 'Mean and gaussian', 0, 50, nothing)

switch = '0:Mean\n1:Gaussian'
cv2.createTrackbar(switch, 'Mean and gaussian', 0, 1, nothing)

while True:
    cv2.imshow('Mean and gaussian', image)

    if cv2.waitKey(1) & 0xFF == 27:
        break
    size = cv2.getTrackbarPos('BlurSize', 'Mean and gaussian')
    sigmaX = cv2.getTrackbarPos('sigmaX', 'Mean and gaussian')
    sigmaY = cv2.getTrackbarPos('sigmaY', 'Mean and gaussian')
    s = cv2.getTrackbarPos(switch, 'Mean and gaussian')
    if s == 0:
        image = imageBlur(backup, size)
    else:
        image = imageGaussianBlur(backup, size, sigmaX, sigmaY)
    

cv2.destroyAllWindows()

 

2번 코드 설명

더보기
# -*- coding: utf-8 -*-
from OpenCV_Functions import *

def nothing(x):
    pass

#이미지 설정
imagePath = "<이미지 경로>"
image = imageRead(imagePath) 
backup = imageCopy(image)

#창 띄우기
cv2.namedWindow('imageMedianBlur', cv2.WINDOW_GUI_EXPANDED)

#트랙바 설정
cv2.createTrackbar('BlurSize', 'imageMedianBlur', 0, 10, nothing)

switch = '0:OFF\n1:On'
cv2.createTrackbar(switch, 'imageMedianBlur', 1, 1, nothing)

while True:
    cv2.imshow('imageMedianBlur', image)

    if cv2.waitKey(1) & 0xFF == 27:
        break
    size = cv2.getTrackbarPos('BlurSize', 'imageMedianBlur')
    s = cv2.getTrackbarPos(switch, 'imageMedianBlur')

    if s == 1:
        image = imageMedianBlur(backup, size)
    else:
        image = backup
    

cv2.destroyAllWindows()