我写的卷积函数

2024-06-25 22:47:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了一个卷积的代码,但是它没有给出正确的输出。你知道吗

代码:

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)

我想它会给人一个模糊的印象。你知道吗


Tags: 代码inimgfornpoutcv2kernel
1条回答
网友
1楼 · 发布于 2024-06-25 22:47:07

你的问题是它没有被正确识别。。。。所以它只做一个像素然后返回。。。正确的代码应为:

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函数来优化卷积。你知道吗

相关问题 更多 >