Question: I have an image of connected components(circles filled).If i want to segment them i can use watershed algorithm.I prefer writing my own function for watershed instead of using the inbuilt function in OPENCV.I have successfu How do i find the regionalmax of objects using opencv?

Answer: 
The following listing is a function similar to Matlab's "imregionalmax". It looks for at most **nLocMax** local maxima above **threshold**, where the found local maxima are at least **minDistBtwLocMax** pixels apart. It returns the actual number of local maxima found. Notice that it uses OpenCV's **minMaxLoc** to find global maxima. It is "opencv-self-contained" except for the (easy to implement) function **vdist**, which computes the (euclidian) distance between points (r,c) and (row,col).

**input** is one-channel CV\_32F matrix, and **locations** is nLocMax (rows) by 2 (columns) CV\_32S matrix.

```html
int imregionalmax(Mat input, int nLocMax, float threshold, float minDistBtwLocMax, Mat locations)
{
    Mat scratch = input.clone();
    int nFoundLocMax = 0;
    for (int i = 0; i < nLocMax; i++) {
        Point location;
        double maxVal;
        minMaxLoc(scratch, NULL, &maxVal, NULL, &location);
        if (maxVal > threshold) {
            nFoundLocMax += 1;
            int row = location.y;
            int col = location.x;
            locations.at<int>(i,0) = row;
            locations.at<int>(i,1) = col;
            int r0 = (row-minDistBtwLocMax > -1 ? row-minDistBtwLocMax : 0);
            int r1 = (row+minDistBtwLocMax < scratch.rows ? row+minDistBtwLocMax : scratch.rows-1);
            int c0 = (col-minDistBtwLocMax > -1 ? col-minDistBtwLocMax : 0);
            int c1 = (col+minDistBtwLocMax < scratch.cols ? col+minDistBtwLocMax : scratch.cols-1);
            for (int r = r0; r <= r1; r++) {
                for (int c = c0; c <= c1; c++) {
                    if (vdist(Point2DMake(r, c),Point2DMake(row, col)) <= minDistBtwLocMax) {
                        scratch.at<float>(r,c) = 0.0;
                    }
                }
            }
        } else {
            break;
        }
    }
    return nFoundLocMax;
}
```
I do not know if it is what you want, but in my answer to [this post](https://stackoverflow.com/questions/10313602/reshaping-noisy-coin-into-a-circle-form/10324759#10324759), I gave some code to find local maxima (peaks) in a grayscale image (resulting from distance transform).
The approach relies on subtracting the original image from the dilated image and finding the zero pixels).
I hope it helps,
Good luck