Reputation: 33
I am trying to apply NMF to a particular image that is loaded in grayscale mode. I have tried several links but my image after application of NMF remains almost the same and cannot be distinguished with the grayscale image initially loaded.
However, when i come across the scikit-learn's code on implementing decomposition on a dataset, i see that the faces there have been transformed into ghost - like faces. Here is the link:
And here is the code I am using:
import cv2
from sklearn import decomposition
import matplotlib.pyplot as plt
img = cv2.imread('test1.jpeg',0)
estimator = decomposition.NMF(n_components = 2, init = 'nndsvda', tol = 5e-3)
estimator.fit(img)
vmax = max(img.max(), -img.min())
plt.imshow(img, cmap=plt.cm.gray, interpolation = 'nearest',vmin=-vmax,vmax=vmax)
plt.show()
I am new to the techniques of NMF on matrices espicially such a large image numpy array.
My image is test1.jpeg that is 225 * 224 .jpeg image.
Can someone please help me on implementing the code for a single image? Thanks a lot in advance.
Upvotes: 2
Views: 2784
Reputation: 339340
The reason you get the original image in the plot is that you actually plot the original image. Instead you would need to work with the output of estimator
.
The NMF decomposition produces two matrices W
and H
that compose the original matrix. You need to multiply those to get the image.
import cv2
from sklearn import decomposition
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread('data/trump2.jpg',0)
vmax = max(img.max(), -img.min())
fig, (ax, ax2) =plt.subplots(ncols=2)
ax.imshow(img, cmap=plt.cm.gray, interpolation = 'nearest',vmin=-vmax,vmax=vmax)
n_components = 20
estimator = decomposition.NMF(n_components = n_components, init = 'random', tol=5e-3)
W = estimator.fit_transform(img)
H = estimator.components_
new_img = np.dot(W,H)
ax2.imshow(new_img, cmap=plt.cm.gray,
interpolation='nearest',
vmin=-vmax, vmax=vmax)
plt.show()
Upvotes: 3