Use PCA (Principal Component Analysis) to blur color image
阿新 • • 發佈:2018-12-31
I wrote an example of blurring color picture by using PCA from scikit-learn:
Python12345678910111213 | 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:
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