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

    Join Date
    Oct 2013
    Posts
    1
    Rep Power
    0

    How to count the number of dots in an image


    Hi,

    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
    Posts
    194
    Rep Power
    2
    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.

    http://en.wikipedia.org/wiki/Flood_fill

    -Mek

    Edit:
    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()
        image.set_colorkey(color)
        mask = pg.mask.from_surface(image)
        mask.invert()
        return len(mask.connected_components())

    Comments on this post

    • b49P23TIvg agrees : Excellent!
    Last edited by Mekire; October 3rd, 2013 at 03:45 AM.
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,856
    Rep Power
    481
    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