python - 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()
解决方案
感谢@Knight Forked 的评论,我的方法没有任何计算错误,但这是因为我直接将“输出”分配给了我的地址。将 output = I 更改为 output = I.copy() 将解决我之前遇到的问题。
# output = I
output = I.copy()
我认为问题的发生是因为每次我计算输出时,它指的是我的地址而不是输出本身。
推荐阅读
- c++ - 如何在不复制太多代码的情况下重构此代码?
- arrays - 数组到索引值对的字符串
- visual-studio-code - 我可以执行由 CSV/Excel 文件驱动的查找/替换吗?
- python - Python 在导入的模块中找不到子模块
- amazon-web-services - ECS容器中运行的服务抛出java.io.IOException: Too many open files
- python - ValueError:尝试从 django 中的另一个应用程序导入模型时尝试相对导入超出顶级包
- linux - 在 Raspberry Pi OS 启动时播放视频
- github - 尝试在 github 桌面中将 4 个提交变基为一个时出现问题
- javascript - 如何使用javascript输入字段
- javascript - 在 JS 中获取和修改 iframe 内容