卷积滤镜在图像上的实现

时间:2020-09-01 06:58:20

标签: python opencv

我正在用Python实现图像过滤的卷积逻辑,但每次仅针对不同的输入图像和内核渲染黑色图像。需要帮忙。下面是代码

def convolution_filter(gray_img,kernel):
 img_ht,img_wt = gray_img.shape;
 kernel_ht, kernel_wt = kernel.shape;
 out_img = np.zeros(shape=gray_img.shape)
 k =int((kernel_ht-1)/2);

fl_kernel = kernel;
flip_code = -1;

bdr = int((kernel_wt-1)/2)
v_anchor = (kernel_ht-1)/2
gray_img = cv2.copyMakeBorder(gray_img, bdr, bdr, bdr, bdr,cv2.BORDER_REPLICATE)

for i in range(bdr,img_ht+bdr):
    for j in range(bdr,img_wt+bdr):
        center=gray_img[i-bdr:i+bdr+1, j-bdr:j-bdr+1]
        convolve = (center*kernel).sum()
        
        out_img[i-bdr,j-bdr] = convolve
        out_img = (out_img * 255).astype("uint8")

        
        return out_img;

'''

1 个答案:

答案 0 :(得分:0)

问题:


  • Backspace


    • 假设我的过滤器<div class="block-1" contenteditable="true"> 1st Block </div> <div class="block-2" contenteditable="true"> 2nd Block </div> <div class="block-3" contenteditable="true"> 3rd Block </div> <div class="block-4" contenteditable="true"> 4th Block </div> 不能使用kernel_ht, kernel_wt = kernel.shape;
    • 因为,过滤器的大小为3 x 3,高度= [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]],宽度= kernel.shape
    • 可能的问题: 等待,为什么宽度为len(kernel)len(kernel[0])会是什么?
    • 可能的答案 通常,内核的高度和宽度是相同的。但您可以添加:
      len(kernel[0])
  • if len(kernel[1]) != len(kernel[0]) is True


  • 该代码默认为内核的9个值选择3个变量,其他内核值均乘以0。

  • 例如:对于第一次迭代,选择了kernel_wt = [len(i) for i in kernel if len(i) > len(kernel[0])]像素值,但是我们有9个内核值。 convolve = (center * kernel).sum()因此结果为0,图像为空白

  • 卷积如何工作?


  • enter image description here

  • source

  • 从上面的gif图片可以看出,伪代码为:

  • [114, 114, 144]
  • 左输入图像,内核114 * (-1) + 114 * (0) + 114 * (-1) + 0 * -2 * 0 + 0 * 0 + 2 * 0....的右过滤图像


  • enter image description here enter image description here

  • 代码:


for each iteration: 
    Select 3 x 3 area
    Multiply with the kernel
    image(current_coordinates) = multiplication.