我为卷积编写的函数给出了错误

时间:2019-04-23 07:34:17

标签: python opencv

我已经为卷积编写了代码,但是没有给出正确的输出。

代码:

def convolve(img , kernel):
    (ih , iw) = img.shape[:2]
    (kh , kw) = kernel.shape[:2]

    pad = (kw - 1) // 2
    img = cv2.copyMakeBorder(img , pad , pad , pad , pad , cv2.BORDER_REPLICATE)
    out = np.zeros((ih , iw) , dtype = "float32")

    for y in np.arange(pad , ih + pad):
        for x in np.arange(pad , iw + pad):
            roi = img[y - pad: y + pad + 1 , x - pad : x + pad + 1]
            res = (roi * kernel).sum()

            out[y - pad, x - pad] = res
            out = rescale_intensity(out, in_range=(0, 255))
            out = (out * 255).astype("uint8")

            return out

我将此函数称为:

smallblur_kernel = np.ones((3 , 3) , dtype = "float") * (1.0 / (3 * 3))
ans = convolve(gray , smallblur_kernel)

我希望它会产生模糊的图像。

1 个答案:

答案 0 :(得分:3)

您的问题是它的标识不正确...。因此它仅处理一个像素并返回...正确的代码应为:

import numpy as np
import cv2
from skimage import exposure

def convolve(img , kernel):
    (ih , iw) = img.shape[:2]
    (kh , kw) = kernel.shape[:2]

    pad = (kw - 1) // 2
    img = cv2.copyMakeBorder(img , pad , pad , pad , pad , cv2.BORDER_REPLICATE)
    out = np.zeros((ih , iw) , dtype = "float32")

    for y in np.arange(pad , ih + pad):
        for x in np.arange(pad , iw + pad):
            roi = img[y - pad: y + pad + 1 , x - pad : x + pad + 1]
            res = (roi * kernel).sum()

            out[y - pad, x - pad] = res
    ##### This lines were not indented correctly #####
    out = exposure.rescale_intensity(out, in_range=(0, 255))
    out = (out*255 ).astype(np.uint8)
    ##################################################
    return out

smallblur_kernel = np.ones((3 , 3) , dtype = "float") * (1.0 / (3 * 3))
gray = cv2.imread("D:\\debug\\lena.png", 0)
ans = convolve(gray , smallblur_kernel)
cv2.imshow("a", ans)
cv2.waitKey(0)
cv2.destroyAllWindows()

但是此功能非常慢,您应该使用OpenCV中的filter2d函数来优化卷积。