python中对单个图像的非负矩阵分解

2024-04-25 05:08:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将NMF应用于以灰度模式加载的特定图像。我尝试了几个链接,但我的图像在应用NMF后几乎保持不变,无法与最初加载的灰度图像区分开来。在

然而,当我看到scikitlearn关于在数据集上实现分解的代码时,我看到那里的面已经被转换成了鬼魂般的脸。以下是链接:

http://scikit-learn.org/stable/auto_examples/decomposition/plot_faces_decomposition.html#sphx-glr-auto-examples-decomposition-plot-faces-decomposition-py

下面是我使用的代码:

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()

我对矩阵上的NMF技术很陌生,尤其是这样一个大的图像numpy数组。
我的图像是test1.jpeg,即225*224.jpeg图像。在

有人能帮我实现一个图像的代码吗? 事先非常感谢。在


Tags: 代码图像importimgautoplot链接plt
1条回答
网友
1楼 · 发布于 2024-04-25 05:08:45

在绘图中获得原始图像的原因是您实际绘制了原始图像。相反,您需要使用estimator的输出。在

NMF分解产生两个矩阵W和{},它们构成原始矩阵。你需要把它们相乘才能得到图像。在

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()

enter image description here

相关问题 更多 >