Search code examples
setmembership

set's membership seems not to work (python)


I am working on a image search algorithm that finds certain shapes of certain colors; to save time I only register half of the shape's perimeter in 2 distinct sets, one for the rows and one for the columns used by the shape. The idea is that whenever I find a point which has the target color, I then check if this point's row and column are in a master set (which have both the previous sets); if they are I skip it, if they are not then I initialize 2 recursive fuctions that register the first row and the first column of the shape.

Since it's for a school project, my images are specially tailored

and the code would be

for y in range(height):
    for x in range(width):
        if img[y][x] == target:
            if y in master_set and x in master_set:
                continue
            else:
                row = set()
                column = set()
                flood_fillv2_y(img,x,y,target,column)
                flood_fillv2_x(img,x,y,target,row)
                row=frozenset(row)
                column=frozenset(column)
                master_set.add(row)
                master_set.add(column)

The idea then is to check the len of master_set to see how many shapes I have, but as I said what I get is that y and x are never in the master set so it keeps doing it for all points of the shape, resulting in a wrong number.


Solution

  • It's hard to give a good answer without seeing the whole code, but I can give a guess:

    master_set.add(row) literally adds the frozenset row to the master_set, but you probably want all elements from the set to be added to master_set. Take a look at the update() method of sets.

    Does this help?