How do I write this in OpenCV with Python?
Date: 2022-12-13 11:58:46
How do I write the following MATLAB piece of code in Python by using OpenCV ? I have problems with the last line of code, I don't know how to implement that 'single' function. Can you help me ? Thanks.
img = imread(''); grayImage = rgb2gray(img); kernel1 = -1 * ones(3)/9; kernel1(2,2) = 8/9 filteredImage = imfilter(single(grayImage), kernel1);
My code looks as following, what I tried so far:
import cv2 import numpy as np img = cv2.imread('', 0); kernel1 = np.ones((3,3), np.float32)/9 kernel1[1][1] = 0.8888889 filteredImage = cv2.filter2D(img, -1, kernel1)
Answer:
Here is the MATLAB version:
img = rgb2gray(imread('peppers.png')); kernel = -ones(3)/9; kernel(2,2) = 8/9; out = imfilter(single(img), kernel1); imshow(out, []) % <-- note automatic image rescaling
Here is the python version:
import numpy as np import cv2 img = cv2.imread("peppers.png", 0) kernel = np.ones((3,3), np.float32) / -9.0 kernel[1][1] = 8.0/9.0 out = cv2.filter2D(img.astype(np.float32), -1, kernel) out = (out - out.min()) / (out.max() - out.min()) cv2.imshow("image", out) cv2.waitKey(0)