Quantcast
Channel: Robin on Linux
Viewing all articles
Browse latest Browse all 237

Use PCA (Principal Component Analysis) to blur color image

$
0
0

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

import cv2
import numpy as np

from sklearn.decomposition import PCA

pca = 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

ValueError: Found array with dim 3. Estimator expected <= 2.

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

img = cv2.imread('input.jpg')

shape = img.shape
img_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

Viewing all articles
Browse latest Browse all 237

Trending Articles