Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving multiple values in an array using openCV

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading