Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python separate round particles by offsetting contours / shrinking polygones

I'm new to python and stuck..

I want to make a python script that allows me to separate adjacent particles on an image like this:

BEFORE

into separate regions like this:

AFTER

I was suggested to use the watershed method, which as far as I understand it would give me a something like this:

Watershed in 3D

EDIT Actually found out that this is distance transform and not watershed

Where I then could use a threshold to separate them.. Followed this openCV watershed guide but it only worked to cut out the particles. Was not able to "transform" the code to do what I want.

I then took another approach. Tried to use the openCV contours which gave me good contours of the particles. I have then been looking intensively for an easy way to perform polygon offset in order to shrink the edge like this:

Edge offset

Using the center from the offset contours (polygon) should give me the number of particles.. But I just haven been able to find a simple way to do edge offset / polygon shrinking with python.

like image 787
Norfeldt Avatar asked Oct 07 '12 19:10

Norfeldt


1 Answers

Here is a script using numpy, scipy and the scikit-image (aka skimage). It makes use of local maxima extraction and watershading plus labeling (ie connected components extraction).

import numpy as np
import scipy.misc
import scipy.ndimage
import skimage.feature
import skimage.morphology

# parameters
THRESHOLD = 128

# read image
im = scipy.misc.imread("JPh65.png")
# convert to gray image
im = im.mean(axis=-1)
# find peaks
peak = skimage.feature.peak_local_max(im, threshold_rel=0.9, min_distance=10)
# make an image with peaks at 1
peak_im = np.zeros_like(im)
for p in peak:
    peak_im[p[0], p[1]] = 1
# label peaks
peak_label, _ = scipy.ndimage.label(peak_im)
# propagate peak labels with watershed
labels = skimage.morphology.watershed(255 - im, peak_label)
# limit watershed labels to area where the image is intense enough
result = labels * (im > THRESHOLD)
like image 132
Nicolas Barbey Avatar answered Oct 04 '22 18:10

Nicolas Barbey