我刚看到this示例并尝试使用Dictionary Learning
对图像进行去噪。此代码适用于灰度图像,但不适用于3香奈儿或彩色图像。
这是我的代码=>
from time import time
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from sklearn.decomposition import MiniBatchDictionaryLearning
from sklearn.feature_extraction.image import extract_patches_2d
from sklearn.feature_extraction.image import reconstruct_from_patches_2d
from sklearn.utils.fixes import sp_version
from sklearn.datasets import load_sample_image
from scipy import ndimage
from skimage import color
from skimage import io
from PIL import Image
from sklearn.decomposition import SparseCoder
from sklearn.decomposition import sparse_encode
from skimage import data,restoration
from scipy.misc import imfilter, imread
from scipy.signal import convolve2d as conv2
from skimage import data, img_as_float
from skimage.restoration import denoise_nl_means
from scipy import ndimage as ndi
from skimage import feature
c = np.asarray(Image.open('starfish.jpg'))
n0 = np.asarray(Image.open('starfish.jpg'))
c = c / 255
n0 = n0 / 255
height, width, chanel = n0.shape
n0 = n0 + 0.075 * np.random.randn(height, width, chanel)
patchsize = (7,14)
t0 = time()
data = extract_patches_2d(c,(7,14))
data = data.reshape(data.shape[0], -1)
data = data - np.mean(data, axis=0)
data = data / np.std(data, axis=0)
t1 = time()
print('Total time : ',round((t1-t0),2),' sec')
print('Learning the dictionary ....')
t2 = time()
n_iter = 1000
dico = MiniBatchDictionaryLearning(n_components=100,alpha=2,n_iter=n_iter)
V = dico.fit(data).components_
print(V.shape)
t3 = time()
print('No of iteration : ',n_iter)
print('Total time taken for Dictionary learning : ',round((t3-t2),2),' sec')
t4 = time()
n0_data = extract_patches_2d(n0,(7,14))
print(n0_data.shape)
print(n0_data)
n0_data = n0_data.reshape(n0_data.shape[0], -1)
intercept = np.mean(n0_data, axis=0)
n0_data = n0_data - intercept
dico.set_params(transform_algorithm='omp',transform_n_nonzero_coefs = 1)
code = dico.transform(n0_data)
patches = np.dot(code,V)
patches = patches + intercept
print(patches)
print(patches.shape)
print(patches[0].shape)
patches = patches.reshape(len(n0_data), *patchsize)
result = reconstruct_from_patches_2d(patches,(height, width))
denoise = denoise_nl_means(result, 1, 9, 0.08, multichannel=True)
edge =feature.canny(denoise,sigma=3)
print(edge)
plt.imshow(result,cmap='gray')
plt.show()
print('Total time taken for sparse modeling : ',round((time()-t4),2))
如果我使用
进行灰度转换,那么相同的代码工作正常此行=>
c = np.asarray(Image.open('starfish.jpg').convert('L'))
n0 = np.asarray(Image.open('starfish.jpg').convert('L'))
错误是=>
文件" color.py",第103行,
patches = patches.reshape(len(n0_data),* patchsize)
ValueError:新数组的总大小必须保持不变
我该如何解决这个问题?