user2096230
user2096230

Reputation: 57

loop binary image pixel

i have this image with two people in it. it is binary image only contains black and white pixels.

first i want to loop over all the pixels and find white pixels in the image.

than what i want to do is that i want to find [x,y] for the one certain white pixel.

after that i want to use that particular[x,y] in the image which is for the white pixel in the image.

using that co-ordinate of [x,y] i want to convert neighbouring black pixels into white pixels. not whole image tho.

i wanted to post image here but i cant post it unfortunately. i hope my question is understandable now. in the below image you can see the edges.

say for example the edge of the nose i find that with loop using [x,y] and than turn all neighbouring black pixels into white pixels.

This is the binary image

Upvotes: 1

Views: 1257

Answers (1)

mmgp
mmgp

Reputation: 19241

The operation described is called dilation, from Mathematical Morphology. You can either use, for example, scipy.ndimage.binary_dilation or implement your own.

Here are the two forms to do it (one is a trivial implementation), and you can check the resulting images are identical:

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])

Upvotes: 3

Related Questions