Showing posts with label opencv. Show all posts
Showing posts with label opencv. Show all posts

Thursday, July 19, 2012

Playing around with opencv convexity defects

Modifying a little the code of the previous post, removes the points too close to the convex hull:
Edit the end of the script as follow:

    cv2.line(img,start,end,[255,0,0],1)
    if d>1000:
        cv2.circle(img,far,3,[0,0,255],2)

Friday, July 6, 2012

Convexity defects in a cluster of mouse chromosomes

Just a little trial to explore cv2.convexityDefects() on a cluster of mouse chromosomes:

The cluster consists in five touching mouse chromosomes. The aim is to use cv2 to display the contour of the particle, its convex hull, and to see what it is possible to do with convexityDefects function implemented in OpenCv 2.4.2 which provides now the big advantage of handling numpy array. The python script used is largely inspired from abid rahman's blog:

# -*- coding: utf-8 -*-
"""
Created on Wed Jul  4 14:43:42 2012

@author: jean-pat
"""

import cv2
import numpy as np
import os
import pylab as plb
print cv2.__version__

user=os.path.expanduser("~")
workdir=os.path.join(user,"QFISH","JPPAnimal","JPP52","11","DAPI","particles")

file="part25.png"
complete_path=os.path.join(workdir,file)

img = cv2.imread(complete_path)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,gray = cv2.threshold(gray,1,255,0)
print ret
gray2 = gray.copy()
mask = np.zeros(gray.shape,np.uint8)

contours, hier = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
print hier
cv2.drawContours(img,contours,0,(0,255,0),1)
cnt = contours[0]
hull = cv2.convexHull(cnt,returnPoints = False)
#print hull
approx = cv2.approxPolyDP(cnt,0.05*cv2.arcLength(cnt,True),True)
print 'approx',approx

print 'contours',type(cnt), cnt.dtype, len(contours)
defects = cv2.convexityDefects(cnt,hull)
print defects
for i in range(defects.shape[0]):
    s,e,f,d = defects[i,0]
    start = tuple(cnt[s][0])
    end = tuple(cnt[e][0])
    far = tuple(cnt[f][0])
    cv2.line(img,start,end,[255,0,0],1)
    cv2.circle(img,far,5,[0,0,255],1)

plb.imshow(img)
plb.show()

    
The result is :

Strangely, some convexity defects (blue circles) of the particle contour (green curve) are very close to the particle convex hull (red curve). Four defects are detected on the contour where the chromosomes touch each other as waited. Those contact regions correspond to "neck" on the contour curve, and only one side of the neck is detected.
At first sight, there is nine false positive points, four well detected points and four non detected points (the other side of the "necks").

From the script, the content of the defect variable is:

[[[  214   216   215   689]]
[[  216   218   217   114]]
[[    0    30    19  2444]]
 [[   30    32    31   234]]
 [[   32    34    33   201]]
 [[   34    38    37   278]]
 [[   38    71    56  5658]]
 [[   72    78    73   114]]
 [[   78    94    87  3133]]
 [[   96    98    97   114]]
 [[   98   106   101   297]]
 [[  106   120   111   364]]
 [[  121   212   179 12452]]]

The convexity defect is a list of vectors of the form:

(start_index, end_index, farthest_pt_index, fixpt_depth)

so it should be possible to filter the points too close to the convex hull.

Building OpenCv 2.4.2 on Ubuntu 12.04

In Ubuntu 12.04 only OpenCv 2.3 is available. To exploit the examples in Abid Rahman's blog, at least OpenCv 2.4 is necessary.
To install OpenCV 2.4.2, open you package manager (synaptics) and uninstall if necessary previous OpenCv version. Check if the required/optionnal libraries are installed, for example:
                          
                          Commit Log for Wed Jul  4 21:38:54 2012

                          Les paquets suivants ont été installés :
                          libtbb-dev (4.0+r233-1)
                          libtbb-doc (4.0+r233-1)
                          libtbb2 (4.0+r233-1)
                          tbb-examples (4.0+r233-1)

cmake must be installed, it's convenient to install cmake-gui too. Download OpenCv 2.4.x (here 2.4.2) and uncompress the archive in some directory. Make an other directory to build OpenCV:

For example, in a directory called Applications,  the OpenCv source code is in OpenCv-2.4.2 and an empty directory Build OpenCv242.
Run cmake-gui, it can be found from the dash:

looking for CMake with the Dash

Once cmake run, select the directory containing OpenCv source code, and the target directory that will contain the build OpenCv:

CMake gui running after having selected the source code directory and the build directory
Within cmake, check the different options that are needed (tiff support, python ...), click on the configure button, then on generate. If everything went fine, open the destination directory, open a console in it and type the commands:

                                                        make
then 
                                                         sudo make install

The options selected can be found in the CMakeCache.txt file.

The installation can be checked by opening a ipython shell and importing cv2 as follow:
ipython shell after cv2 importation
The auto completion can find some function implemented in OpenCv (cv2).

Tuesday, May 31, 2011

A minimal use of opencv: toward chromosome shape analysis.

In an attempt to analyse the chromosomes shape, I need to access to the coordinates of points belonging to the contour or to the skeleton of chromosomes. Opencv is a rich vision library, usable from python. Here, I wrote a minimal script to access the pixels of the chromosome contour:
part15.png:image used to test opencv

import cv
definition of some colors
_red =  (0, 0, 255, 0);
_green =  (0, 255, 0, 0);
_white = cv.RealScalar (255)
_black = cv.RealScalar (0)
# create window and display the original picture in it
path="/home/claire/Applications/ProjetPython/test opencv/part15.png"
image = cv.LoadImage(path,cv.CV_LOAD_IMAGE_GRAYSCALE)
binary=image>0
cv.NamedWindow ("image", 1)
cv.ShowImage ("image", image)
# create the storage area
storage = cv.CreateMemStorage (0)
# find the contours
contours = cv.FindContours(image,
                               storage,
                               cv.CV_RETR_TREE,
                               cv.CV_CHAIN_APPROX_SIMPLE,
                               (0,0))
cv.DrawContours(image,contours,_red,_black,max_level=2)
print len(contours)
print contours[0],contours[1],contours[61]
cv.WaitKey (0)

  • The first thing I noticed is that without cv.WaitKey(0), the image is not visible, it is displayed and erased immediately.
  • The object contours is a list of pixels coordinates, I didn't check yet if it is an ordered list of pixels.
My feeling about opencv is that it is a world itself, may be not mixing very well with other library.