Reputation: 99
I have a binary image and I need to find the mean values of x and y of the black region. These values are calculated for a set of binary images and their mean values of x and y are plotted I don't know how to find this region and calculate their mean values of x and y. Any help is kindly appreciated.
Upvotes: 0
Views: 1351
Reputation: 21203
You can obtain the mean positions using the moments of contours.
In order to find the mean you must calculate the first order moments of the contour.
CODE:
#---Read image and obtain threshold---
im = cv2.imread('1.jpg', 1)
img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img, 120, 255, 1)
#---Obtain contours---
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = contours
cv2.drawContours(im, contours, -1, (0, 255, 0), 1)
#---Compute the center/mean of the contours---
for c in cnts:
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
print cX
print cY
Values cX
and cY
have the mean positions of the contours.
Upvotes: 1
Reputation: 80232
If black pixels are not registered in some data structure, just calculate center of mass for black pixels:
sx = 0
sy = 0
black_cnt = 0
for y in y-range
for x in x-range
if black(x,y)
sx = sx + x
sy = sy + y
black_cnt++
sx = sx / black_cnt
sy = sy / black_cnt
Upvotes: 1