Two pass connected component algorithm is detecting separate components in one image, and after each detection i am saving every component
as a different image. To
I'm not sure I fully understand your code, but I think there might be a simple fix to your problem of too many variables and if
statements. Instead of using separate variables and code to save each of your images, you should put them in lists and index those lists to get at the values to update and save.
Here's how that might look for your code:
# at some point above, create an "images" list instead of separate Zero, One, etc variables
# also create a "counts" list instead of count, count1, etc
for (x, y) in labels:
component = uf.find(labels[(x, y)])
labels[(x, y)] = component
# optionally, add code here to create a new image if needed
images[component][y][x] = 255 # update image
counts[component] += 1 # update count
if counts[component] > 43: # if count is high enough, save out image
img = images[component] = Image.fromarray(Zero)
img.save(os.path.join(dirs, 'image{:02d}.png'.format(component), 'png')
Note that you need to generate the image filenames programmatically, so instead of Zero.png
and One.png
, etc, I went for image00.png
and image01.png
. You could probably create a mapping from numbers to English names if you wanted to keep the same name system, but I suspect using digits will be more convenient for your later use anyway.
If you don't know how many images and counts you need ahead of time, you could add some extra logic to the loop that would create a new ones as needed, appending them to the images
and counts
lists. I put a comment in the code above showing where you'd want that logic.