mike
mike

Reputation: 61

Finding the Blob Centroid

What is the algorithm for finding a blob's centroid (center of mass)?

formula

I found the above equation but I don't know how to translate it into VB 6.0. I looked online for a simple centroid algorithm in VB 6.0, but I did not find one that calculates the value of X and Y coordinates.

I tried to do the above algo in VB6.0. However, it always gives 1 as the center.:

Private Sub FindCentroid(bmp As PictureBox)

Dim area As Double
Dim x As Integer, y As Integer
Dim Xc, Yc, Xs, Ys As Integer

area = 0
For y = 0 To bmp.ScaleHeight - 1
    For x = 0 To bmp.ScaleWidth - 1
If bmp.Point(x, y) = vbWhite Then area = area + 1

Next x: Next y

Xs = 0
For y = 0 To bmp.ScaleHeight - 1
    For x = 0 To bmp.ScaleWidth - 1
        If bmp.Point(x, y) = vbWhite Then Xs = Xs + 1
 Next x
Next y

Ys = 0

For y = 0 To bmp.ScaleWidth - 1
    For x = 0 To bmp.ScaleHeight - 1

        If bmp.Point(y, x) = vbWhite Then Ys = Ys + 1

Next x
Next y

Xc = Xs / area
Yc = Xs / area

End Sub

Upvotes: 0

Views: 2851

Answers (2)

wckd
wckd

Reputation: 410

If you look at your code you repeat yourself three times. First for area, second for Xs, and third for Ys. Secondly your code does not match the equation you provided.

Try something like this:

For y = 0 To bmp.ScaleHeight - 1
  For x = 0 To bmp.ScaleWidth - 1
    If bmp.Point(x, y) = vbWhite 
      Then 
        Xs = Xs + x
        Ys = Ys + y
        area = area + 1
    endIF
  Next x
Next y

I don't know VB syntax so you'll have to adjust that a bit.

UPDATE

To complete the algorithm normalize by area:

Ys = Ys / area
Xs = Xs / area

Upvotes: 3

Ophir Gvirtzer
Ophir Gvirtzer

Reputation: 622

You have two bugs in your code:

  1. You wrote

    Xs = Xs + 1

instead of

Xs = Xs + X

2. the same for y

Other than that, the code is fine

Upvotes: 0

Related Questions