续上一篇文章,需要将一张400*400的图像转为400*10像素的图片,如果用Opencv中的resize也可以做到,只是最终形成的图片形式是未知的,仅作个人实验笔记记录。
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 24 00:49:04 2020
@author: YQLiang
"""
from sklearn.decomposition import PCA
import cv2 as cv
import numpy as np
def showImage(img):
cv.namedWindow('img', 0)
cv.resizeWindow('img', 400,400)
cv.imshow("img", img)
cv.waitKey()
#PCA简单例子
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca1 = PCA(n_components=2)
newX = pca1.fit_transform(X)
print(pca1.explained_variance_ratio_)
#print(newX)
#验证
pca2 = PCA(n_components=1)
newX2 = pca2.fit_transform(X)
print(pca2.explained_variance_ratio_)
#print(newX2)
img = cv.imread('C:\\Users\\YQLiang\\Desktop\\timg.jpg',0)
height, width = img.shape[:2]
print(height,width)
imgArray = []
for i in range(0, height):
templist = []
for j in range(0, width):
templist.append(img[i][j])
imgArray.append(templist)
pca = PCA(n_components=10)
newArray = pca.fit_transform(imgArray)
print(pca.explained_variance_ratio_)
#转为图像
new_image = np.around(newArray)
new_image = new_image.astype(np.uint8)
showImage(img)
showImage(new_image)
#前后尺寸
height, width = img.shape[:2]
print(height,width)
height1, width1 = new_image.shape[:2]
print(height1,width1)
运行结果:
原图
经过PCA处理之后的图
runfile('E:/PyCharm/PythonFile/pca.py', wdir='E:/PyCharm/PythonFile')
[0.99244289 0.00755711]
[0.99244289]
400 400
[0.28629053 0.16941406 0.06003207 0.04780086 0.03895499 0.02815717
0.02660091 0.02303981 0.01843251 0.0182951 ]
400 400
400 10
思路:PCA降维->聚类->返回原图观测同类的图片是否相似。