Sort blobs generated by cvBlobsLib by areas.

May 18, 2011

cvBlobsLib is an useful OpenCV 3rd party library to do blob analysis. However the blobs extracted are sorted based on their y coordinates and the author provided no interface to sort the blobs by other criteria such as area. To do so, you need to make some internal change. Add the following member function that sort the blobs based on their areas to the class CBlobResult.

    // sort blobs
    void SortBlobs()
    {
        struct myclass {
            bool operator() (CBlob* b1,CBlob* b2)
            {
                return (b1->GetArea() < b2->GetArea());
            }
        } blobComp;

        std::sort(m_blobs.begin(),m_blobs.end(),blobComp);
    }

If you want to sort the blobs based on their x coordinates, change the 7th line of above code to

return (b1->GetBoundingBox().x < b2->GetBoundingBox().x);

.


Be aware of memory alignment of IplImage in OpenCV

May 7, 2008

The imageData of IplImage is aligned 4 or 8 bytes in order to enhance the processing speed. For example, let’s say you have a color image of size 98-by-98 (pixel depth 8 bits ) and imageData is aligned 4 bytes. The size of each row will not be 98×3=294 bytes but 296 bytes. The widthStep of IplImage shows the actual size of aligned image row in bytes. This can help us access imageData correctly. Here is a code that copy imageData to a user-created buffer.

//
IplImage *colorImage;
// load an color image
colorImage = cvLoadImage("SL_0230.jpg");
// create a temp buffer
unsigned char *buffer,*temp2;
buffer = new unsigned char[colorImage->width*colorImage->height*colorImage->nChannels];
temp2 = buffer;

// pointer to imageData
unsigned char *temp1 = (unsigned char*) colorImage->imageData;
// copy imagedata to buffer row by row
for(int i=0;i<colorImage->height;i++)
{
    // memory copy
    memcpy(temp2, temp1, colorImage->width*colorImage->nChannels);
    // imageData jump to next line
    temp1 = temp1 + colorImage->widthStep;
    // buffer jump to next line
    temp2 = temp2+ colorImage->width*colorImage->nChannels;
}
// ......................
//.....