gpt4 book ai didi

python - 在 PGM 格式文件中实现扩张过滤器

转载 作者:行者123 更新时间:2023-12-04 10:36:54 31 4
gpt4 key购买 nike

我目前正在做一个学生项目,它对灰度 pgm 文件进行一些图像处理(膨胀和腐 eclipse )。我试图对图像对象实现扩张,但得到了奇怪的结果。我预计图像对象会比原始图像大。但是根据我使用的内核大小,我得到了对象的多个副本。

原图:

Original Picture

膨胀结果:

Dilation Result

这是我的扩张源代码

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)

Axial_68.pgm

我非常确定我的文件读取和写入功能正常工作,因为我可以使用它来正确读取和写入其他源 pgm 文件。

我发现非常奇怪的一件事是我可以像这样打印半个 pgm 文件。

Half Horizontal

使用代码
    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

我懂了:

Half vertical

我已经用其他一些生成的 pgm 文件尝试过这个,结果都是一样的。
我想知道我的膨胀代码是否与这种奇怪的行为有关。

最佳答案

它总是有助于直接显示矩阵,而不是依靠您自己编写的例程将其写入文件以供检查。例如,添加

import matplotlib.pyplot as pp
#...
a = pgm_read("Axial_68.pgm")
pp.imshow(a)
pp.show()

您的代码立即显示输入图像未正确读取。交换 reshape 中的两个维度函数调用为我修复了它:

return np.array([line.strip('\n') for line in lines[4:]], dtype=np.int32).reshape(int(header_info[1]),
int(header_info[0]))

我强烈建议您使用库来读取和写入图像文件。例如 imageio是个不错的选择。 Matplotlib 本身也可以读写各种图像文件格式。
如果你想做图像处理,也可以得到一个库。例如 Pillow , OpenCVDIPlib .这些都还包括图像文件读写功能。

关于python - 在 PGM 格式文件中实现扩张过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60132897/

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