这个函数将bace_path内所有影像进行主成分分析后转为灰度图保存在save_path
import numpy as np
import cv2
from scipy import linalg
import os
def t_to_png(bace_path,save_path):
f_n = os.listdir(bace_path)
print(f_n)
del f_n[-1]
for name in f_n:
print("name: ",name)
im_path = bace_path + name
im_save = save_path + name.split('.')[0] + ".png"
print(im_path)
img = cv2.imread(im_path, cv2.IMREAD_COLOR)
nrows, ncolumns = img.shape[0:2]
imgArrT = np.array(img, dtype=np.int64).reshape(-1, 3)
mean = np.mean(imgArrT, axis=0)
CenterImg = imgArrT - mean
covar = np.matmul(np.transpose(CenterImg), CenterImg)
evalues, evectors = linalg.eig(covar)
principle_xis = evectors[:, np.argmax(evalues)]
principle_xis = principle_xis / np.sum(principle_xis)
principle_xis = principle_xis[:, np.newaxis]
principle_img = np.matmul(imgArrT, principle_xis)
principle_img = np.uint8(principle_img.reshape((nrows, ncolumns)))
grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite(im_save,grayimg)
print(im_save)
cv2.waitKey(0)