Computer's Guy
Computer's Guy

Reputation: 5363

Algorithm for detecting edge of shape in image with PIL in python when separation < 1 px

This is kind of an easy problem to solve, i'm trying to re-arrange shapes in a plane but first i need to detect them in the right way, i've came up with this very inefficient algorithm but it does the job fine until it reaches two shapes that are separated by a distance that is < 1px:

Here you have it in python pseudocode:

#all pixels
for x in range(0, image.width):
    for y in range(0, image.height):

        if pixel is black:
            # mark start of shapes

        else:
            if shape is open:
                for r in range (0, image.height):
                    if pixel is black:
                        # found shape, keep shape open
                    else:
                        # close shape
            else:
                for r in range (0, image.height):
                    paint pixel gray # this draws the vertical gray lines in the example

This is the resulting image:

enter image description here

As you can see, the grey bars are drawn between the shapes but it doesn't work when two shapes are too close together (with a distance of less than 1px between each other)

IMPORTANT: I don't need to make this work for shapes that overlap vertically.

I dont really care about the python/pillow syntax if you can explain really well what your algorithm does and how it works and it looks like python / PIL code.

Upvotes: 3

Views: 2636

Answers (1)

Sneftel
Sneftel

Reputation: 41552

It sounds like you want to look at both the current column of pixels, and the previous one. If there's no y-position that's black in both columns, it's a new shape (or no shape).

Upvotes: 3

Related Questions