Center Of Mass In Contour (Python, OpenCV)
I have this image:  What I am trying to do is to detect the center of mass of the inner contour (number 3) inside it. This is the code I have right now: import cv2 import numpy as
Solution 1:
You can try by taking the average of contour points, mentioned here.
  imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  ret, thresh = cv2.threshold(imgray, 127, 255, 0, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
  _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
  cnts = cv2.drawContours(image, contours[0], -1, (0, 255, 0), 1)
  kpCnt = len(contours[0])
  x = 0
  y = 0
  for kp in contours[0]:
    x = x+kp[0][0]
    y = y+kp[0][1]
  cv2.circle(image, (np.uint8(np.ceil(x/kpCnt)), np.uint8(np.ceil(y/kpCnt))), 1, (0, 0, 255), 3)
  cv2.namedWindow("Result", cv2.WINDOW_NORMAL)
  cv2.imshow("Result", cnts)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

Post a Comment for "Center Of Mass In Contour (Python, OpenCV)"