I am trying to apply min filter to some images using the OpenCV library. How can I implement a min filter in Python using OpenCV? Is there any function to do that? If not, how can I write one?
I am trying to apply min filter to some images using the OpenCV library. How can I implement a min filter in Python using OpenCV? Is there any function to do that? If not, how can I write one?
By min filter I guess you mean running a kernel through each location in an image and replacing the kernel centre with the min value within the kernel's pixels.
To achieve this in Opencv you simply can use, cv2.erode. Documentation here.
But first, you need to define the size and shape of the kernel. You use cv.getStructuringElement doc here:
Example:
size = (3, 3)
shape = cv2.MORPH_RECT
kernel = cv2.getStructuringElement(shape, size)
min_image = cv2.erode(image, kernel)
In addition to the previous answers, I implement in python + opencv the code that applies the minimum and maximum box filter.
import cv2
def minimumBoxFilter(n, path_to_image):
img = cv2.imread(path_to_image)
# Creates the shape of the kernel
size = (n, n)
shape = cv2.MORPH_RECT
kernel = cv2.getStructuringElement(shape, size)
# Applies the minimum filter with kernel NxN
imgResult = cv2.erode(img, kernel)
# Shows the result
cv2.namedWindow('Result with n ' + str(n), cv2.WINDOW_NORMAL) # Adjust the window length
cv2.imshow('Result with n ' + str(n), imgResult)
def maximumBoxFilter(n, path_to_image):
img = cv2.imread(path_to_image)
# Creates the shape of the kernel
size = (n,n)
shape = cv2.MORPH_RECT
kernel = cv2.getStructuringElement(shape, size)
# Applies the maximum filter with kernel NxN
imgResult = cv2.dilate(img, kernel)
# Shows the result
cv2.namedWindow('Result with n ' + str(n), cv2.WINDOW_NORMAL) # Adjust the window length
cv2.imshow('Result with n ' + str(n), imgResult)
if __name__ == "__main__":
path_to_image = 'images/africa.tif'
print("Test the function minimumBoxFilter()")
minimumBoxFilter(3, path_to_image)
minimumBoxFilter(5, path_to_image)
minimumBoxFilter(7, path_to_image)
minimumBoxFilter(11, path_to_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
print("Test the function maximumBoxFilter()")
maximumBoxFilter(3, path_to_image)
maximumBoxFilter(5, path_to_image)
maximumBoxFilter(7, path_to_image)
maximumBoxFilter(11, path_to_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
where path_to_image is a string. For example: 'images/africa.tif'
I obtain the following results:
With the minimum filter: