0

I have a following image:

enter image description here

I would like to find the center of the main object in the image - the book in this case.

I follow this answer: Center of mass in contour (Python, OpenCV)

and try:


import cv2
import numpy as np

image = cv2.imread("29289.jpg")


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), 30)


cv2.namedWindow("Result", cv2.WINDOW_NORMAL)
cv2.imshow("Result", cnts)
cv2.waitKey(0)
cv2.destroyAllWindows()

But the result is a nonsense (see the red point which should be the center):

enter image description here

Do you have any idea how to solve this problem? Thanks a lot

vojtam
  • 1,157
  • 9
  • 34
  • Find the largest contour: cnt = max(contours, key=cv2.contourArea) – iohans Jan 25 '23 at 15:05
  • You should debug and enhance your preprocessing steps. The thresholding is - in this case - not suited very well to separate object and background – MSpiller Jan 25 '23 at 15:07
  • Did you look at your threshold image? Does it discriminate the book from the hand and the background? – fmw42 Jan 25 '23 at 16:49

0 Answers0