首页 > 解决方案 > Python:实现扩张方法的问题

问题描述

该方法采用原始图像和 elem 过滤器。对于膨胀,如果任何重叠的输入像素值为 1/255,则新的中心像素值为 1/255。我在下面编写的方法会遍历每个像素,如果发现任何重叠,则将过滤中心设置为 255。但是,我最终得到了一个大的白色方块。

我认为这行有问题:
output[i + ((eCol-1)//2), j+((eRow-1)//2)] = 255。将其替换为 ' output[i+m, j+n] = 255 ' 不会改变原始图像。

import numpy as np
import cv2 as cv
import math
import matplotlib.pyplot as plt

# Mat I, Mat elem
#the new center pixel value is 1 if any of the overlapping input pixel values is 1.
def Dilate(I, elem):
    # TODO
    iCol = I.shape[0];
    iRow = I.shape[1];

    eRow = elem.shape[0]
    eCol = elem.shape[1]
    
    row = iRow - eRow + 1
    col = iCol - eCol + 1
    output=I
    
    #print (eCol)
    #print (eRow)
    for i in range(0, col):
        for j in range(0, row):

            for m in range (0, eCol):
                for n in range (0, eRow):
                    
                    if I[i+m,j+n] == elem[m][n] == 1:
                        output[i+(eCol-1)//2, j+(eRow-1)//2] = 1
                    elif I[i+m,j+n] == 255 and elem[m][n] == 1:
                        output[i + ((eCol-1)//2), j+((eRow-1)//2)] = 255    
    return output

# test.bmp is a binary or black and white image
I = cv.imread("test.bmp", cv.IMREAD_GRAYSCALE)

elem1= np.array( 
        [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

DilateI = Dilate(I,elem1)

output = cv.cvtColor(DilateI, cv.COLOR_BGR2RGB)
plt.axis('off')
plt.imshow(output)
plt.show()

原图 失败的图片 演示

标签: pythonopencv

解决方案


感谢@Knight Forked 的评论,我的方法没有任何计算错误,但这是因为我直接将“输出”分配给了我的地址。将 output = I 更改为 output = I.copy() 将解决我之前遇到的问题。

# output = I 
output = I.copy()

我认为问题的发生是因为每次我计算输出时,它指的是我的地址而不是输出本身。


推荐阅读