1. 程式人生 > >Use PCA (Principal Component Analysis) to blur color image

Use PCA (Principal Component Analysis) to blur color image

I wrote an example of blurring color picture by using PCA from scikit-learn:

Python
12345678910111213 importcv2importnumpy asnpfromsklearn.decomposition importPCApca=PCA(n_components=0.96)img=cv2.imread("input.jpg")reduced=pca.fit_transform(img)res=pca.inverse_transform(reduced)cv2.imwrite('output.jpg',res.reshape(shape))

But it reports

1 ValueError:Found arraywith dim3.Estimator expected<=2.

The correct solution is transforming image to 2 dimensions shape, and inverse transform it after PCA:

Python
123456 img=cv2.imread('input.jpg')shape=img.shapeimg_r=img.reshape((shape[0],shape[1]*shape[2]))reduced=pca.fit_transform(img_r)

It works very well now. Let’s see the original image and blurring image:



Original Image



Blurring Image