简体   繁体   中英

Function I have wrote for Convolution giving error

I have written a code for Convolution, but it is not giving proper output.

Code:

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

I am calling this function as:

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

I expect it to give a blurred image.

Your issue is that it is not correctly idented.... so it only does one pixel and returns... the correct code should be:

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()

However this function is pretty slow, you should use the filter2d function from OpenCV to have an optimized convolution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM