1

I am trying to save the x,y positions of the centroids of a series of images using OpenCV.

My code is:

import cv2 as cv
import glob
import numpy as np
import os

#---------------------------------------------------------------------------------------------

# Read the Path

path1 = r"D:\Direction of folder" 

for file in os.listdir(path1): # imagens from the path 
    if file.endswith((".png",".jpg")): # Images formats 

        # Reed all the images 

        Image = cv.imread(file)

        # RGB to Gray Scale
        
        GS = cv.cvtColor(Image, cv.COLOR_BGR2GRAY)
        th, Gray = cv.threshold(GS, 128, 192, cv.THRESH_OTSU)
        
        # Gray Scale to Bin

        ret,Binari = cv.threshold(GS, 127,255, cv.THRESH_BINARY)

        # Moments of binary images

        M = cv.moments(Binari)

        # calculate x,y coordinate of center

        cX = [int(M["m10"] / M["m00"])]
        cY = [int(M["m01"] / M["m00"])]

#---------------------------------------------------------------------------------------------

How can I store all x,y positions of the variables cX and cY in an array?

1
  • 1
    Create an empty list. Append cX and cY for each object as a tuple (cX, cY) to the list. Finally, convert the list to an array using numpy: array = np.asarray(list) Commented May 11, 2022 at 13:16

1 Answer 1

3

Create two empty lists before the for loop as follows:

cXs, cYs = [], []
for file in os.listdir(path1): 

Append the values after the cX and cY lines as follows:

    cX = [int(M["m10"] / M["m00"])]
    cY = [int(M["m01"] / M["m00"])]
    cXs.append(cX)
    cYs.append(cY)

You can use them after the end of the for loop. For example:

print(cXs)
print(cYs)

You can convert them to numpy arrays, if required, as follows:

cXs = np.array(cXs)
cYs = np.array(cYs)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.