【发布时间】:2021-12-08 13:10:25
【问题描述】:
我正在为美国的鹿种创建一个图像分类模型,我目前正在对这些图像执行 PCA,以减少它们的内存大小并减少模型的运行时间。
我知道主成分分析应该在不放弃太多方差的情况下减少数据集的维度。因此,当我注意到通过我的Deer_PCA 函数运行的所有新 PCA 压缩图像都比原始图像大时,我有点困惑。原始图像为 128 KB,新的压缩图像在 n_components = 150 运行后为 293 KB。有谁知道为什么会这样?
这是我在函数中运行的图片,在运行代码之前将图片放在一个空文件夹中:
这是通过Deer_PCA 函数运行后的新压缩图像:
这是我的代码:
#import some packages
import cv2
import os,sys
from PIL import Image
import pandas as pd
from scipy.stats import stats
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
#Let's write a function to perform PCA on all the images in the folder and output it to a new folder
#inpath = folder containing the image - string value
#outpath = which folder do I want the new compressed image saved to. - string value
#n_comp = number of components - int value
def Deer_PCA(inpath, outpath,n_comp):
for image_path in os.listdir(inpath):
# create the full input path and read the file
input_path = os.path.join(inpath, image_path)
print(input_path)
w_deer = cv2.cvtColor(cv2.imread(input_path), cv2.COLOR_BGR2RGB)
#split image
blue_2,green_2,red_2 = cv2.split(w_deer)
#scale channels
w_blue = blue_2/255
w_green = green_2/255
w_red = red_2/255
#PCA on each channel
pca_b2 = PCA(n_components=n_comp)
pca_b2.fit(w_blue)
trans_pca_b2 = pca_b2.transform(w_blue)
pca_g2 = PCA(n_components=n_comp)
pca_g2.fit(w_green)
trans_pca_g2 = pca_g2.transform(w_green)
pca_r2 = PCA(n_components=n_comp)
pca_r2.fit(w_red)
trans_pca_r2 = pca_r2.transform(w_red)
#merge channels after PCA
b_arr2 = pca_b2.inverse_transform(trans_pca_b2)
g_arr2 = pca_g2.inverse_transform(trans_pca_g2)
r_arr2 = pca_r2.inverse_transform(trans_pca_r2)
img_reduced2 = (cv2.merge((b_arr2, g_arr2, r_arr2)))
print("Merge Successful")
# create the full output path
fullpath = os.path.join(outpath, 'PCA_'+image_path)
cv2.imwrite(fullpath, img_reduced2*255)
print("Successfully saved\n")
#Check the image sizes
original_image_path = '/Users/matthew_macwan/Downloads/CIS/I_Class_Deer/mule_deer_doe/mule deer doe_1.jpeg'
PCA_compressed_image_path = '/Users/matthew_macwan/Downloads/CIS/I_Class_Deer/mule_deer_doe/PCA_mule deer doe_1.jpeg'
print('Original Image:',sys.getsizeof(original_image_path))
print('PCA Image:',sys.getsizeof(PCA_compressed_image_path))
【问题讨论】:
-
您处理了一张我们看不到的图像并获得了另一张我们也看不到的图像,您想知道为什么一张更大?来吧——如果你想让人们帮助你,让他们轻松一点。谢谢。
-
我很抱歉。我不是一个真正使用 StackOverflow 的人。无论我使用什么图像,PCA 压缩后的图像总是比原始图像大。所以我认为问题出在代码上,并且认为信息就足够了。我会上传图片。
-
我不确定您将 PCA 单独应用于每个通道并在之后重新组合的方法是否合法。通常,您会使用 PCA 来降低维度,例如您可能有一个 225 通道的高光谱图像,并希望将其减少到只有 3 个通道,其中包含大部分方差以进行可视化。您似乎将通道分开处理并保留它们,这似乎不太可能减少任何东西。我很可能是错的,并且可能还有其他一些我不知道的 PCA 用途。也许 Fred @fmw42 会发表评论?
标签: python image machine-learning image-processing pca