【问题标题】:Min filter in Python using OpenCV使用 OpenCV 在 Python 中使用最小过滤器
【发布时间】:2020-07-17 11:37:35
【问题描述】:

我正在尝试使用 OpenCV 库将最小过滤器应用于某些图像。如何使用 OpenCV 在 Python 中实现最小过滤器? 有什么功能可以做到这一点吗? 如果没有,我怎么写?

【问题讨论】:

  • 也许你想要 Numpy np.amin()。

标签: python image opencv image-processing filtering


【解决方案1】:

形态侵蚀是最小过滤器。在 OpenCV 中,这是在函数 erode 中实现的。

【讨论】:

    【解决方案2】:

    min filter 我猜你的意思是通过图像中的每个位置运行内核,并用内核像素内的最小值替换内核中心。

    要在 Opencv 中实现这一点,您只需使用 cv2.erode。文档here。

    但首先,您需要定义内核的大小和形状。你用cv.getStructuringElement doc here:

    例子:

    size = (3, 3)
    shape = cv2.MORPH_RECT
    kernel = cv2.getStructuringElement(shape, size)
    min_image = cv2.erode(image, kernel)
    

    【讨论】:

      【解决方案3】:

      除了前面的答案,我在python + opencv中实现了应用最小和最大框过滤器的代码。

      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()
      

      其中 path_to_image 是一个字符串。例如:'images/africa.tif'

      我得到以下结果:

      使用最小过滤器:

      使用最大过滤器:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-20
        • 1970-01-01
        • 2014-05-04
        • 2016-02-03
        相关资源
        最近更新 更多