我正在嘗試使用 OpenCV 保存一系列影像的質心的 x,y 位置。
我的代碼是:
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"])]
#---------------------------------------------------------------------------------------------
如何將變數 cX 和 cY 的所有 x,y 位置存盤在陣列中?
uj5u.com熱心網友回復:
在回圈之前創建兩個空串列for,如下所示:
cXs, cYs = [], []
for file in os.listdir(path1):
cX在和行之后附加值cY,如下所示:
cX = [int(M["m10"] / M["m00"])]
cY = [int(M["m01"] / M["m00"])]
cXs.append(cX)
cYs.append(cY)
for您可以在回圈結束后使用它們。例如:
print(cXs)
print(cYs)
如果需要,您可以將它們轉換為numpy陣列,如下所示:
cXs = np.array(cXs)
cYs = np.array(cYs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472812.html
