1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Rep Power

    How to count the number of dots in an image


    I am trying to write a script in Python to count the number of red (255,0,0) dots in an image. These are not pixels, but dots, so don't want to run through each pixel and check, which might also be slow. I so far have read a couple of posts and searched the Internet, but failed to find a complete solution. I have tried using scipy, numpy, and PIL libraries.

    Can someone help me put some code together? Thanks in advance.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Rep Power
    There may be a better way to do this, but you might consider looking into flood fill algorithms.

    This is the type of algorithm used for the paint bucket tool in paint programs. You might be able to use a similar cellular automata to find your connected regions of colors.



    If you are working with pygame, this can do it. Might be a bit annoying otherwise, as it won't work without an active pygame window.
    python Code:
    import pygame as pg
    def count_dots(filename, color):
        image = pg.image.load(filename).convert()
        mask = pg.mask.from_surface(image)
        return len(mask.connected_components())

    Comments on this post

    • b49P23TIvg agrees : Excellent!
    Last edited by Mekire; October 3rd, 2013 at 04:45 AM.
  4. #3
  5. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Rep Power
    That easy, really? Wow.

    it's easier for me to think in terms of "red". With "red" equivalent to "color",

    The idea is to find a red dot in the part of the picture not yet visited, flood fill the red from there marking the sites as "visited", and repeat until all sites have been visited.

    There may be additional measurable characteristics of each region that make it constitute a "dot".
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo