How to build a kernel size for an opencv Medianblur filter

Asked

Viewed 35 times

0

I have this Medianblur filter in opencv:

import cv2

img = cv2.imread('Resources/land.jpg')
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


def empty(a):
    pass

# ------- CREATE TRACKBAR -------
cv2.namedWindow('Median Blur')
cv2.createTrackbar('Median', 'Median Blur', 0, 10, empty)

while True:
    m_pos = cv2.getTrackbarPos('Median', 'Median Blur')

    imgMedianBlur = cv2.medianBlur(imgGray, 5)
    cv2.imshow('Median Blur', imgMedianBlur)
    cv2.waitKey(1)

I put a fixed parameter 5 in kernel size ksize:

imgMedianBlur = cv2.medianBlur(imgGray, 5)

I’m trying to dynamically place this value with Trackbar’s position:

m_pos = cv2.getTrackbarPos('Median', 'Median Blur')
# recebendo a pos do trackbar

But of course putting m_pos (below) does not work:

imgMedianBlur = cv2.medianBlur(imgGray, m_pos)

with that mistake:

error: (-215:Assertion failed) (ksize % 2 == 1) && (_src0.dims() <= 2 )

How I build this kernel size based on the position of trackbar?

am using - Pycharm Community 2019.3 - Mac - Python 3.7 - module: opencv-python 4.4.0

1 answer

1

Solved. It was enough to leave the m_pos odd, as indicated in error (ksize % 2 == 1).

The code went like this:

m_pos = cv2.getTrackbarPos('Median', 'Median Blur')
    if(m_pos % 2 != 1):
        m_pos = m_pos + 1

    imgMedianBlur = cv2.medianBlur(imgGray, m_pos)

I’ll leave the answer here in case someone needs it too!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.