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, -1],
[-1, -1, -1]])
i'm new to opencv so if you can explain that'd be great. thanks!
As far as applying a custom kernel to a given image you may simply use filter2D method to feed in a custom filter. You may also copy the following code to get you going. But The results with current filter seem a bit weird:
import cv2
import numpy as np
# Create a dummy input image.
canvas = np.zeros((100, 100), dtype=np.uint8)
canvas = cv2.circle(canvas, (50, 50), 20, (255,), -1)
kernel = np.array([[-1, -1, -1],
[-1, 4, -1],
[-1, -1, -1]])
dst = cv2.filter2D(canvas, -1, kernel)
cv2.imwrite("./filtered.png", dst)
Input image:
Output Image:
EDIT: As per the edits suggested by @Dolphin, using a kernel with center value of 8, would get the good results in case of circular binary disc.
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: