I am trying to calculate the center of gravity by extracting the contours of multiple figures using python and opencv.
The photo in symmetry with the program is as follows.

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread ("test.jpg")
gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold (img, 127, 255, 0)
img1 = np.array (thresh)
img2 = cv2.cvtColor (img1, cv2.COLOR_BGR2GRAY)

contours, _ = cv2.findContours (img2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
M = cv2.moments (c)
x = int (M ["m10"]/M ["m00"])
y = int (M ["m01"]/M ["m00"])
plt.plot (x, y, marker ='.')

plt.imshow (img2, cmap = "gray")
plt.colorbar ()
plt.show ()

The error appears on the 6th line and is displayed as follows

gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV (4.2.0) C: \ projects \ opencv-python \ opencv \ modules \ imgproc \ src \ color.cpp: 182: error: (-215: Assertion failed)! _src.empty () in function 'cv :: cvtColor'

It's just the beginning, so I can't tell even the rudimentary mistakes. I would be happy if you could tell me in detail. Also, if you have any other code mistakes, please let me know.