-2

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)
drgs
  • 117
  • 1
  • 10
  • you could probably use `img.astype(np.float32)` to convert the numpy array to single-precision floating point type – Amro Jul 13 '14 at 13:17
  • It doesn't work, unfortunately. The entire image gets white with only some black dots on it. – drgs Jul 13 '14 at 13:19
  • that depends on how you're displaying the image afterwards, you might need to rescale it to [0.0,1.0] range – Amro Jul 13 '14 at 13:20

1 Answers1

2

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

matlab

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)

python_opencv

Amro
  • 123,847
  • 25
  • 243
  • 454
  • It worked, thank you so much ! My mistake was that I forgot to put that minus sign at the kernel. – drgs Jul 13 '14 at 13:53