我目前正在做一个学生项目,对灰度 pgm 文件进行一些图像处理(膨胀和侵蚀)。我试图在图像对象上实现膨胀,但得到了奇怪的结果。我预计图像对象会比原始图像大。但是我得到了对象的多个副本,具体取决于我使用的内核大小。
原图:
膨胀结果:
这是我的膨胀源代码
import numpy as np
def pgm_read(filename):
"""Read PGM file to a array"""
# Performance Bottleneck: I/O system calls, parallel write/read
try:
with open(filename, 'r') as fp:
lines = fp.readlines()
header_info = lines[2].split()
return np.array([line.strip('\n') for line in lines[4:]], dtype=np.int32).reshape(int(header_info[0]),
int(header_info[1]))
except OSError:
print("An exception occurred")
def pgm_write(img, dest, header):
"""Write numpy array to PGM file"""
try:
header = "P2\n# test\n" + header + "\n80\n"
f = open(dest, "w")
f.write(header)
f.close()
with open(dest, "a") as f:
for x in range(img.shape[0]):
for y in range(img.shape[1]):
f.write(str(img[x][y]) + "\n")
except OSError:
print("Writing exception occurred")
def dilation(img):
rows, cols = img.shape
dilated_img = np.zeros((rows, cols), dtype=np.int32)
kernel = np.ones((2, 2))
rows2, cols2 = kernel.shape
for x in range(rows):
for y in range(cols):
"""Search the object within the image"""
if img[x][y] == 1:
# Convolve with kernel
for i in range(rows2):
for j in range(cols2):
if kernel[i][j] == 1:
# Object Enlargement
c = x + i
d = y + j
if c < rows and d < cols:
dilated_img[c][d] = 1
for x in range(rows):
for y in range(cols):
"""Give the object brightest colour for debugging purpose"""
if dilated_img[x][y] == 1:
dilated_img[x][y] = 80
return dilated_img
if __name__ == '__main__':
a = pgm_read("Axial_68.pgm")
a = dilation(a)
target = "Axial_68_1.pgm"
header = "265 490"
pgm_write(a, target, header)
我非常确定我的文件读取和写入功能可以正常工作,因为我可以使用它来正确读取和写入其他源 pgm 文件。
我发现非常奇怪的一件事是我可以像这样打印半个 pgm 文件。
使用代码
for x in range(rows // 2):
for y in range(columns):
arr[x][y] = 80
但是当我使用此代码并期望使用代码半垂直时:
for x in range(rows):
for y in range(columns // 2):
arr[x][y] = 80
我懂了:
我已经用其他一些生成的 pgm 文件尝试过这个,结果都是一样的。我想知道我的膨胀代码是否与这种奇怪的行为有关。