How to make a new filter and apply it on an image using cv2 in python2.7?

后端 未结 2 1709
臣服心动
臣服心动 2021-01-03 04:24

How to make a new filter and apply it on an image using cv2 in python2.7?

For example:

kernel = np.array([[-1, -1, -1],
                   [-1,  4, -         


        
2条回答
  •  半阙折子戏
    2021-01-03 05:09

    You can just adapt the code at http://docs.opencv.org/3.1.0/d4/d13/tutorial_py_filtering.html. That is an OpenCV 3 page but it will work for OpenCV 2.

    The only difference in the code below is how the kernel is set.

    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    img = cv2.imread('opencv_logo.png')
    
    kernel = np.ones((3,3),np.float32) * (-1)
    kernel[1,1] = 8
    print(kernel)
    dst = cv2.filter2D(img,-1,kernel)
    
    plt.subplot(121),plt.imshow(img),plt.title('Original')
    plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(dst),plt.title('Filters')
    plt.xticks([]), plt.yticks([])
    plt.show()
    

    Notice that I have used 8 for the centre pixel instead of 4, because using 4 darkens the results too much. Here is the result from the code above:

提交回复
热议问题