Search code examples
pythonopencvblobdetection

Blob detection with python opencv


Anyone knows a way do detect blobs with python cv opencv lib? Initally I don't want use external lib as cvBlobs.

I'm working on a license plate recognition and have some images processed like that enter image description here

and want separate the blobs to catch the plate.

I've yet made it using AForge in C#:

BlobCounterBase bc = new BlobCounter();
bc.FilterBlobs = true;
bc.MinHeight = 5;
bc.MinWidth = 5;

bc.ProcessImage(bitmap);
Blob[] blobs = bc.GetObjectsInformation();
for (int i = 0, n = blobs.Length; i < n; i++)
{
    if (blobs.Length > 0)
    {              
        bc.ExtractBlobsImage(bitmap, blobs[i], true);
        Bitmap copy = blobs[i].Image.ToManagedImage();
        Console.WriteLine(blobs[i].Rectangle.Size.ToString());
        copy.Save("C:/Users/Marcilio/Desktop/segmentacao/" + i + ".jpg");
    }
}
bitmap.Save("C:/Users/Marcilio/Desktop/foto2.jpg");

And now I need the equivalent to python's opencv.


Solution

  • OpenCV has the findContours function which returns a list of contours and their hierarchy.

    Once you have the contours, you can get their moments (e.g. to calculate the centroid), their areas, their convexity and everything else you need.

    So your code would look something like this (untested):

    contours, _ = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    for c in contours:
        rect = cv2.boundingRect(c)
        if rect[2] < 5 or rect[3] < 5: continue
        print cv2.contourArea(c)