Do you think that's a good way to solve this problem ?
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main (int argc,char **argv)
{
Mat x = imread("14415468805620458.jpg",CV_LOAD_IMAGE_GRAYSCALE);
imshow("original", x);
Mat y,cc;
double ccMin, ccMax;
threshold(x, y, 50, 255, THRESH_BINARY);
imshow("threshold", y);
Mat labels1, labels2;
connectedComponents(y, labels1, 8, CV_32S);
minMaxIdx(labels1, &ccMin, &ccMax);
bitwise_not(y, y);
connectedComponents(y, labels2, 8, CV_32S);
Mat mask = labels1 == 0;
add(labels2, ccMax, labels2, mask);
labels1 = labels1 + labels2 - 1;
minMaxIdx(labels1, &ccMin, &ccMax);
cout<<ccMax<<"\n";
labels1.convertTo(cc, CV_8UC1, 32, 0);
applyColorMap(cc, cc, cv::COLORMAP_HSV);
imshow("Labels", cc);
waitKey(0);
}