如何将图像转换为数据集以处理机器学习

时间:2017-08-26 15:08:22

标签: python image numpy image-processing machine-learning

如何将图像转换为数据集或numpy数组并通过将其设置为clf进行预测

import PIL as pillow
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

infilename=input()
im=Image.open(infilename)
imarr=np.array(im)
flatim=imarr.flatten('F')

clf=svm.SVC(gamma=0.0001,C=100)
x,y=im.size

#how to fit the numpy array to clf 
clf.fit(flatim[:-1],flatim[:-1])
print("prediction:",clf.predict(flatim[-1]))
plt.imshow(flatim,camp=plt.cm.gray_r,interpolation='nearest')
plt.show()

任何人都请,谢谢!

1 个答案:

答案 0 :(得分:1)

除了乐趣之外,没有其他原因可以在单个图像上使用SVM。以下是我所做的修复。 1)使用.convert(" L")将图像转换为2D阵列灰度。 2)创建一个虚拟目标变量y作为随机1D数组。 3)修复类型错误再次显示图像(plt.imshow)cmap(而不是camp)和im(而不是flatim)

import PIL as pillow
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

im=Image.open("sample.jpg").convert("L")
imarr=np.array(im)
flatim=imarr.flatten('F')

clf=svm.SVC()
#X,y=im.size
X = imarr
y = np.random.randint(2, size=imarr.shape[0])
clf.fit(X, y)

#how to fit the numpy array to clf 
#clf.fit(flatim[:-1],flatim[:-1])
# I HAVE NO IDEA WHAT I"M DOING HERE!
print("prediction:", clf.predict(X[-2:-1]))
plt.imshow(im,cmap=plt.cm.gray_r,interpolation='nearest')
plt.show()

我在使用SVM的scikit-learn website中看到了一个很好的例子。我想这就是你要复制的内容。 ISN'?吨