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

<p>For example:</p>

<pre><code>kernel = np.array([[-1, -1, -1],
                   [-1,  4, -1],
                   [-1, -1, -1]])
</code></pre>

<p>i'm new to opencv so if you can explain that'd be great. thanks!</p>

<p>You can just adapt the code at <a href="http://docs.opencv.org/3.1.0/d4/d13/tutorial_py_filtering.html" rel="nofollow">http://docs.opencv.org/3.1.0/d4/d13/tutorial_py_filtering.html</a>.
That is an OpenCV 3 page but it will work for OpenCV 2.</p>

<p>The only difference in the code below is how the kernel is set.</p>

<pre><code>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()
</code></pre>

<p>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:</p>

<p><a href="http://i.stack.imgur.com/o5bNQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/o5bNQ.png" alt="enter image description here"></a></p>

python python-2.7 opencv