【问题标题】:How do I write this in OpenCV with Python?我如何用 Python 在 OpenCV 中编写这个?
【发布时间】:2014-07-13 13:05:34
【问题描述】:

如何使用 OpenCV 在 Python 中编写以下 MATLAB 代码?我的最后一行代码有问题,我不知道如何实现那个“单一”功能。你能帮助我吗 ?谢谢。

img = imread('');
grayImage = rgb2gray(img);
kernel1 = -1 * ones(3)/9;
kernel1(2,2) = 8/9
filteredImage = imfilter(single(grayImage), kernel1);

到目前为止,我的代码如下所示:

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)

【问题讨论】:

  • 你可以使用img.astype(np.float32)将numpy数组转换为单精度浮点类型
  • 很遗憾,它不起作用。整个图像变成白色,上面只有一些黑点。
  • 这取决于您之后如何显示图像,您可能需要将其重新缩放到 [0.0,1.0] 范围

标签: python matlab opencv image-processing code-translation


【解决方案1】:

这是 MATLAB 版本:

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

这里是python版本:

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)

【讨论】:

  • 成功了,非常感谢!我的错误是我忘了把那个减号放在内核中。
猜你喜欢
  • 1970-01-01
  • 2020-09-07
  • 2016-08-12
  • 2011-03-12
  • 2016-07-17
  • 1970-01-01
  • 2015-10-31
  • 2021-04-18
  • 1970-01-01
相关资源
最近更新 更多