Reputation: 21
I am trying to apply a 3x3 filter kernel to an image. The code is interpreted without an error, but I no image is displayed? What can I do?
def main():
imgpath = "g.jpg"
img = cv2.imread(imgpath, 1)
import numpy as np
img = np.array(img, dtype=np.uint8)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
k = np.array(np.ones((11, 11), np.float64))/121
k = np.array(([2, 2, 2], [2, 3, 2], [2, 2, 2]), np.float64)
print(k)
output = cv2.filter2D(img, -1, k)
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('Original Image')
plt.subplot(1, 2, 2)
plt.imshow(output)
plt.title('Filtered Image')
plt.show()
if __name__ == "__main__":
main()
Upvotes: 0
Views: 451
Reputation: 61
Except the missing module import part, basically, your codes are correct.
The output image is as empty as white, right? The root cause is the filtered value larger than RGB range, 0~255.
When applying filter, you should keep the output data range be still fall in 0~255. That is,
k = np.array(([2, 2, 2], [2, 3, 2], [2, 2, 2]), np.float64)
k = k / 19
So, for a simple smooth filter, it will be
k = np.array(([1, 1, 1], [1, 1, 1], [1, 1, 1]), np.float64)
k = k / 9
How about Sobel (in horizontal)?
k = np.array(([1, 0, -1], [2, 0, -2], [1, 0, -1]), np.float64)
Yes, keep k as k.
Back to the start, I suggest you paste also the import part you used. It will help others know your problem doesn't come from missing import:
import cv2
import matplotlib.pyplot as plt
import numpy as np
Upvotes: 2