gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:53 25 4
gpt4 key购买 nike

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

代码:

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)

我希望它能给出模糊的图像。

最佳答案

你的问题是它没有被正确识别......所以它只做一个像素并返回......正确的代码应该是:

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

关于python - 我为卷积编写的函数给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55806333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com