循环处理二值图像像素

1 投票
1 回答
1246 浏览
提问于 2025-04-17 16:46

我有一张图片,上面有两个人。这是一张只有黑白像素的二值图像。

首先,我想遍历所有的像素,找到图像中的白色像素。

接下来,我想找到某个特定白色像素的坐标[x,y]。

然后,我想用这个特定的坐标[x,y],也就是那个白色像素在图像中的位置。

利用这个[x,y]坐标,我想把周围的黑色像素变成白色像素,但不是整个图像都变。

我本来想在这里贴图,但不幸的是我不能。希望我的问题现在能让人明白。在下面的图片中,你可以看到边缘。

举个例子,我可以用循环找到鼻子的边缘,然后把所有邻近的黑色像素变成白色像素。

这是那张二值图像

1 个回答

3

这里讲的操作叫做“膨胀”,这是数学形态学中的一个概念。你可以使用,比如说,scipy.ndimage.binary_dilation这个工具,或者自己动手实现一个。

下面有两种方法可以实现这个操作(其中一种是简单的实现),你可以检查一下得到的图像是一样的:

import sys
import numpy
from PIL import Image
from scipy import ndimage

img = Image.open(sys.argv[1]).convert('L') # Input is supposed to the binary.
width, height = img.size
img = img.point(lambda x: 255 if x > 40 else 0) # "Ignore" the JPEG artifacts.

# Dilation
im = numpy.array(img)
im = ndimage.binary_dilation(im, structure=((0, 1, 0), (1, 1, 1), (0, 1, 0)))
im = im.view(numpy.uint8) * 255
Image.fromarray(im).save(sys.argv[2])

# "Other operation"
im = numpy.array(img)
white_pixels = numpy.dstack(numpy.nonzero(im != 0))[0]
for y, x in white_pixels:
    for dy, dx in ((-1,0),(0,-1),(0,1),(1,0)):
        py, px = dy + y, dx + x
        if py >= 0 and px >= 0 and py < height and px < width:
            im[py, px] = 255
Image.fromarray(im).save(sys.argv[3])

撰写回答