Search code examples
pythonnumpyopencv

How do I write the X and Y coordinates from the contours array into separate arrays?


I have an image that has a stain on it. I have found the coordinates of the center of the spot and would like to find all the coordinates of the border of the spot. In the future, I need these coordinates to calculate the length of the vector from the found center to the point on the border.Using the findContours() function, I get an array of contours. How do I write the X and Y coordinates from the contours array into separate arrays?

Original image:

enter image description here

My code:

import cv2
import numpy as np

img = cv2.imread("/content/test_picture.jpg")

gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# конвертация из серого в бинарное
ret, thresh = cv2.threshold(gray_image, 127, 255, 0) 
# расчет моментов на бинарном изображении
M = cv2.moments(thresh)
#расчет коориднат центра объекта
centrX = int(M["m10"] / M["m00"]) #кооридната Х центра
centrY = int(M["m01"] / M["m00"]) #кооридната Y центра

cv2.circle(img, (centrX, centrY), 2, (255, 0, 0), -1)

contours=cv2.findContours(thresh, cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_NONE)
print(contours[0])

I need to get 2 different arrays: one with X coordinates, the other with Y coordinates


Solution

  • If you don't need whole output of findCoutours

    contours, _ =cv2.findContours(thresh, cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_NONE)
    
    # Stack all contours together
    contours_p = np.vstack(contours).squeeze()
    
    x_coordinates = contours_p[:, 0]
    y_coordinates = contours_p[:, 1]
    

    Else, replace contours with contours[0]

    contours =cv2.findContours(thresh, cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_NONE)
    
    # Stack all contours together
    contours_p = np.vstack(contours[0]).squeeze()
    
    x_coordinates = contours_p[:, 0]
    y_coordinates = contours_p[:, 1]