Ask an expert. Trust the answer.

Your academic and career questions answered by verified experts

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

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 

 


Why Matlabhelpers ?

Our Matlab assignment helpers for online MATLAB assignment help service take utmost care of your assignments by keeping the codes simple yet of high-quality. We offer the most reliable MATLAB solutions to students pursuing their Computer Science course from the Monash University, the University of Sydney, the University of New South Wales, the University of Melbourne; to name a few. Approach us today for best Matlab solutions online!

whatsApp order on matlabhelpers.com

telegram order on matlabsolutions.com