Files
jlengrand.github.io/_posts/2011-11-28-simple-region-growing-implementation-in-python.markdown

16 KiB

layout, status, published, title, author, author_login, author_email, author_url, wordpress_id, wordpress_url, date, categories, tags, comments
layout status published title author author_login author_email author_url wordpress_id wordpress_url date categories tags comments
post publish true A simple region growing implementation in Python Julien Lengrand-Lambert jlengrand julien@lengrand.fr http://www.lengrand.fr 318 http://www.lengrand.fr/?p=318 2011-11-28 13:51:14.000000000 +01:00
OpenCV
Python
Tippy
image processing
tippy
region growing
prototyping
id author author_email author_url date date_gmt content
3155 dg drgalindog@linuxmail.org MjAxMi0xMi0xNSAxMToxMDowMCArMDEwMA== MjAxMi0xMi0xNSAxMDoxMDowMCArMDEwMA== Hi! thank you very much for this work, it is pretty useful! I would like to know if this is the last version of the function, I want to put more than one seed....
id author author_email author_url date date_gmt content
3157 Julien Lengrand-Lambert julien@lengrand.fr http://www.lengrand.fr MjAxMi0xMi0xNSAxMjoxNDo0OCArMDEwMA== MjAxMi0xMi0xNSAxMToxNDo0OCArMDEwMA== Hey ! Really glad it has been useful for you. I haven't touched the code for some time now, but I can think about updating it if you need :). Let me think about it
id author author_email author_url date date_gmt content
3203 dg drgalindog@linuxmail.org MjAxMi0xMi0xNyAyMTozMToyOCArMDEwMA== MjAxMi0xMi0xNyAyMDozMToyOCArMDEwMA== Thank you!! :) I'm running the function for different seeds and obtaining individual images, but still I need to have just one single final output ... best!
id author author_email author_url date date_gmt content
3212 Julien Lengrand-Lambert julien@lengrand.fr http://www.lengrand.fr MjAxMi0xMi0xOCAwOTo0ODozOCArMDEwMA== MjAxMi0xMi0xOCAwODo0ODozOCArMDEwMA== I will have a look at it during the holidays. In the meantime, can't you apply the same algorithm multiple times on your image, and then perform a binary operation? Check it out <a href="http://stackoverflow.com/questions/11262312/opencv-intersection-between-two-binary-images" title="SO intersection images" target="_blank">here</a>, I think that using either an <strong>and</strong> or an <strong>or</strong> operation between your two output images ' will do what you want : merge the results. Let me know ;)
id author author_email author_url date date_gmt content
3214 dg drgalindog@linuxmail.org MjAxMi0xMi0xOCAxMzoxOTowOSArMDEwMA== MjAxMi0xMi0xOCAxMjoxOTowOSArMDEwMA== Thaaanks!!! I will let you know :)
id author author_email author_url date date_gmt content
3536 dg drgalindog@linuxmail.org MjAxMy0wMS0wOSAxNjozNjowMiArMDEwMA== MjAxMy0wMS0wOSAxNTozNjowMiArMDEwMA== Hi! Happy 2013! Since I'm not an expert in opencv and python I couldn't achieve it...these functions requires arrays instead iplimages..... but so far still your library works for my purpose! thank you very much Sorry for late reply.. I was also working on my input image :S Thanks again!
id author author_email author_url date date_gmt content
3539 jll jlengrand@gmail.com MjAxMy0wMS0wOSAxNjo0OToyNyArMDEwMA== MjAxMy0wMS0wOSAxNTo0OToyNyArMDEwMA== Hey, t thanks! Best wishes to you too:) my holidays were busier than expected finally:) What do you want to do exactly!? Do you still need help!? Send me a mail if you need more, I'll answer you:)
id author author_email author_url date date_gmt content
3671 dg drgalindog@linuxmail.org MjAxMy0wMS0xNiAxMDo0NDoyNiArMDEwMA== MjAxMy0wMS0xNiAwOTo0NDoyNiArMDEwMA== Thank you very much for your kindness... :O I didn't find your e-mail address :(... Basically I need to put several seeds in one input image (this is a matrix transformed to image) and obtain a single output image with regions.. the idea is to not have overlapping regions.. So far Im using several seeds using for loop in the part of your code calling the function and obtaining independant outputs, but this is giving me overlapping regions and it would really really useful if I don't have to join output images to a single one manually. If you wish I can write you an email! Thanks again
id author author_email author_url date date_gmt content
3928 Julien Lengrand-Lambert julien@lengrand.fr http://www.lengrand.fr MjAxMy0wMS0yNSAxMToxNDozMCArMDEwMA== MjAxMy0wMS0yNSAxMDoxNDozMCArMDEwMA== Hey, It would help a lot if you could send me a "ready to go" script of what you want to do so that I can see and try to upgrade my script. Something with the upload of the image, and the positions of the seeds you want. Put it on git somewhere and I'll look into it.
id author author_email author_url date date_gmt content
4004 Diana drgalindog@linuxmail.org MjAxMy0wMS0yOCAxMzoyMjowOCArMDEwMA== MjAxMy0wMS0yOCAxMjoyMjowOCArMDEwMA== Now it is already solved! thank you very much again. :)
id author author_email author_url date date_gmt content
4014 Margarita Gonzalez Ramirez margy9003@hotmail.com MjAxMy0wMS0yOSAwMjowNDowNiArMDEwMA== MjAxMy0wMS0yOSAwMTowNDowNiArMDEwMA== Hi, I saw your program and I said that is the program that I need. I compiled in linux (terminal) and I showed those mistakes. Can u help me to solve them? ./testrg.py: line 1: import: command not found from: can't read /var/mail/opencv.cv ./testrg.py: line 4: import: command not found ./testrg.py: line 5: import: command not found ./testrg.py: line 6: import: command not found ./testrg.py: line 8: user_input: command not found ./testrg.py: line 10: img_name: command not found ./testrg.py: line 11: threshold: command not found ./testrg.py: line 12: syntax error near unexpected token `(' ./testrg.py: line 12: `img = cv.LoadImage(img_name, cv.CV_LOAD_IMAGE_GRAYSCALE);' Thanks
id author author_email author_url date date_gmt content
4019 Julien Lengrand-Lambert julien@lengrand.fr http://www.lengrand.fr MjAxMy0wMS0yOSAwOTo0ODo0NCArMDEwMA== MjAxMy0wMS0yOSAwODo0ODo0NCArMDEwMA== Hi, I am not sure what you mean. This code is Python, so you should not have to compile it but run it with python. that means do something like : <code> python testrg.py </code> If you want to be able to use ./testrg.py directly, you need to append a <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)" title="shebang wikipedia" target="_blank">shebang</a> at the beginning of the file: <code> #!/usr/bin/python </code> Hope this helps !
id author author_email author_url date date_gmt content
19038 Pascal hmarois21@hotmail.com http://priveyes.craym.eu MjAxMy0xMC0yOCAxNTowMTo1MCArMDEwMA== MjAxMy0xMC0yOCAxNDowMTo1MCArMDEwMA== Hi ! I'm not understand this part : (the first dist value does nothing ?) TY #add the nearest pixel of the contour in it dist = abs(int(numpy.mean(contour_val)) - mean_reg) dist_list = [abs(i - mean_reg) for i in contour_val ] dist = min(dist_list) #get min distance

Hi all,

Here is a simple example of (simple) Region Growing algorithm in Python. It is part of my current project, called Tippy.

Tippy tries to implement use the power of OpenCV and Python to fasten Computer Vision prototyping. The idea is to get as much result as possible with a minimum of code.

A word about region growing , and this implementation :

This approach to segmentation examines neighboring pixels of initial “seed points” and determines whether the pixel neighbors should be added to the region. The process is iterated on, in the same manner as general data clustering algorithms" Basically, region growing is an iterative method used to extract similar parts of an image. One or several points are chosen as a start. The region then grows until it is finally blocked by the stop criteria. This criteria is generally an inside/outside region comparison (energy, size, . . .). Region growing is massively used in medical imaging, and object detection. Here is an example of application in automatic Mine Hunting, which I worked with last year at TNO.

The following method uses one seed point, defined by the user. The region grows by comparing with its neighbourhood. The chosen criteria is in this case a difference between outside pixel's intensity value and the region's mean. The pixel with minimum intensity in the region neighbouhood is chosen to be included. The growing stops as soon as the difference is larger than a threshold.

In this implementation, a 4-connectivity has been chosen. The 8-connectivity should be included soon. Due to the method itself, only grayscale images may be processed for now. So color images should be converted first. region growing tests with a gnu

Here is the input image, the image with the seed point placed, and the final result!


Here is the region growing function implemented in Tippy:

{% highlight python %} import sys import cv import numpy

def simple_region_growing(img, seed, threshold=1): """ A (very) simple implementation of region growing. Extracts a region of the input image depending on a start position and a stop condition. The input should be a single channel 8 bits image and the seed a pixel position (x, y). The threshold corresponds to the difference between outside pixel intensity and mean intensity of region. In case no new pixel is found, the growing stops. Outputs a single channel 8 bits binary (0 or 255) image. Extracted region is highlighted in white. """

try:
    dims = cv.GetSize(img)
except TypeError:
    raise TypeError("(%s) img : IplImage expected!" % (sys._getframe().f_code.co_name))

# img test
if not(img.depth == cv.IPL_DEPTH_8U):
    raise TypeError("(%s) 8U image expected!" % (sys._getframe().f_code.co_name))
elif not(img.nChannels is 1):
    raise TypeError("(%s) 1C image expected!" % (sys._getframe().f_code.co_name))
# threshold tests
if (not isinstance(threshold, int)) :
    raise TypeError("(%s) Int expected!" % (sys._getframe().f_code.co_name))
elif threshold < 0:
    raise ValueError("(%s) Positive value expected!" % (sys._getframe().f_code.co_name))
# seed tests
if not((isinstance(seed, tuple)) and (len(seed) is 2) ) :
    raise TypeError("(%s) (x, y) variable expected!" % (sys._getframe().f_code.co_name))

if (seed[0] or seed[1] ) < 0 :
    raise ValueError("(%s) Seed should have positive values!" % (sys._getframe().f_code.co_name))
elif ((seed[0] > dims[0]) or (seed[1] > dims[1])):
    raise ValueError("(%s) Seed values greater than img size!" % (sys._getframe().f_code.co_name))

reg = cv.CreateImage( dims, cv.IPL_DEPTH_8U, 1)
cv.Zero(reg)

#parameters
mean_reg = float(img[seed[1], seed[0]])
size = 1
pix_area = dims[0]*dims[1]

contour = [] # will be [ [[x1, y1], val1],..., [[xn, yn], valn] ]
contour_val = []
dist = 0
# TODO: may be enhanced later with 8th connectivity
orient = [(1, 0), (0, 1), (-1, 0), (0, -1)] # 4 connectivity
cur_pix = [seed[0], seed[1]]

#Spreading
while(dist<threshold and size<pix_area):
#adding pixels
    for j in range(4):
        #select new candidate
        temp_pix = [cur_pix[0] +orient[j][0], cur_pix[1] +orient[j][1]]

        #check if it belongs to the image
        is_in_img = dims[0]>temp_pix[0]>0 and dims[1]>temp_pix[1]>0 #returns boolean
        #candidate is taken if not already selected before
        if (is_in_img and (reg[temp_pix[1], temp_pix[0]]==0)):
            contour.append(temp_pix)
            contour_val.append(img[temp_pix[1], temp_pix[0]] )
            reg[temp_pix[1], temp_pix[0]] = 150
    #add the nearest pixel of the contour in it
    dist = abs(int(numpy.mean(contour_val)) - mean_reg)

    dist_list = [abs(i - mean_reg) for i in contour_val ]
    dist = min(dist_list)    #get min distance
    index = dist_list.index(min(dist_list)) #mean distance index
    size += 1 # updating region size
    reg[cur_pix[1], cur_pix[0]] = 255

    #updating mean MUST BE FLOAT
    mean_reg = (mean_reg*size + float(contour_val[index]))/(size+1)
    #updating seed
    cur_pix = contour[index]

    #removing pixel from neigborhood
    del contour[index]
    del contour_val[index]

return reg

{% endhighlight %}

Here is a simple test of the function, using Tippy functions. If you only want to use the function, juste remove the tippy stuff and copy the function in your source. Please note than OpenCV is needed for the function to work ;)

{% highlight python %} import cv

import tippy.segmentations as se import tippy.basic_operations as bo import tippy.display_operations as do

user_input = 0

img_name = "tippy/data/gnu.jpg" threshold = 20 img = cv.LoadImage(img_name, cv.CV_LOAD_IMAGE_GRAYSCALE)

if user_input: seed = bo.mouse_point(img, mode="S") # waits for user click to get seed else: seed = (70, 106)

out_img = se.simple_region_growing(img, seed, threshold)

do.display_single_image(out_img, "Region Growing result") {% endhighlight %}

As you can see, the implementation is rather short in code. An option has been included to let user interactively choose their seed.

Tippy is available here As the project is in its very beginning, only a few functions are implemented for now. But I have a lot more coming for you :).

As you can see in the source, tests are included with each function. Applications notes and examples will shortly be available too. Finally, there is now proper installer for now. Simply add the tippy folder in your sources and include the files you need.

I would be very pleased to find some co-workers. It would allow the library to grow much faster :). So feel free to fork the project ;) And (constructive) comments are of course encouraged too !

See you soon Julien