Home > other >  Saving multiple values in an array using openCV
Saving multiple values in an array using openCV

Time:05-11

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?

CodePudding user response:

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)
  • Related