将一组图像分类为类

时间:2013-04-30 14:16:51

标签: python image classification descriptor pca

我有一个问题,我得到一组图片,需要对这些图片进行分类。

问题是,我对这些图像并不了解。因此,我计划使用尽可能多的描述符,然后对其进行PCA以仅识别对我有用的描述符。

如果有帮助,我可以对很多数据点进行监督学习。但是,图片有可能相互连接。这意味着可能有从Image X到Image X + 1的开发,尽管我希望这可以通过每个Image中的信息进行整理。

我的问题是:

  1. 使用Python时,如何做到最好? (我想首先在速度不成问题的情况下进行概念验证)。我应该使用哪些库?
  2. 是否已有图像分类这样的分类?使用一堆描述符并通过PCA将其烹饪下来的示例?说实话,这部分对我来说有点吓人。虽然我认为python应该已经为我做了类似的事情。
  3. 编辑: 我找到了一个整齐的工具包,我目前正在为此尝试:http://scikit-image.org/那里似乎有一些描述符。有没有办法进行自动特征提取,并根据对目标分类的描述能力对特征进行排名? PCA应该能够自动排名。

    编辑2: 我的数据存储框架现在更加精细了。我将使用Fat系统作为数据库。我将为每个类组合的实例提供一个文件夹。因此,如果图像属于第1类和第2类,则会有一个包含这些图像的文件夹img12。这样我就可以更好地控制每个班级的数据量。

    编辑3: 我找到了一个python的libary(sklearn)的例子,它做了我想做的事情。它是关于识别手写数字。我正在尝试将我的数据集转换为我可以使用的数据集。

    这是我使用sklearn发现的例子:

    import pylab as pl
    
    # Import datasets, classifiers and performance metrics
    from sklearn import datasets, svm, metrics
    
    # The digits dataset
    digits = datasets.load_digits()
    
    # The data that we are interested in is made of 8x8 images of digits,
    # let's have a look at the first 3 images, stored in the `images`
    # attribute of the dataset. If we were working from image files, we
    # could load them using pylab.imread. For these images know which
    # digit they represent: it is given in the 'target' of the dataset.
    for index, (image, label) in enumerate(zip(digits.images, digits.target)[:4]):
        pl.subplot(2, 4, index + 1)
        pl.axis('off')
        pl.imshow(image, cmap=pl.cm.gray_r, interpolation='nearest')
        pl.title('Training: %i' % label)
    
    # To apply an classifier on this data, we need to flatten the image, to
    # turn the data in a (samples, feature) matrix:
    n_samples = len(digits.images)
    data = digits.images.reshape((n_samples, -1))
    
    # Create a classifier: a support vector classifier
    classifier = svm.SVC(gamma=0.001)
    
    # We learn the digits on the first half of the digits
    classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])
    
    # Now predict the value of the digit on the second half:
    expected = digits.target[n_samples / 2:]
    predicted = classifier.predict(data[n_samples / 2:])
    
    print("Classification report for classifier %s:\n%s\n"
          % (classifier, metrics.classification_report(expected, predicted)))
    print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))
    
    for index, (image, prediction) in enumerate(
            zip(digits.images[n_samples / 2:], predicted)[:4]):
        pl.subplot(2, 4, index + 5)
        pl.axis('off')
        pl.imshow(image, cmap=pl.cm.gray_r, interpolation='nearest')
        pl.title('Prediction: %i' % prediction)
    
    pl.show()
    

4 个答案:

答案 0 :(得分:8)

您可以将图片转换为像素矢量,并在该矢量上执行PCA。这可能比尝试手动查找描述符更容易。你可以在python中使用numPy和sciPy。 例如:

import scipy.io
from numpy import *
#every row in the *.mat file is 256*256 numbers representing gray scale values
#for each pixel in an image. i.e. if XTrain.mat has 1000 lines than each line
#will be made up of 256*256 numbers and there would be 1000 images in the file.
#The following loads the image into a sciPy matrix where each row is a vector
#of length 256*256, representing an image. This code will need to be switched
#out if you have a different method of storing images.
Xtrain = scipy.io.loadmat('Xtrain.mat')["Xtrain"]
Ytrain = scipy.io.loadmat('Ytrain.mat')["Ytrain"]
Xtest = scipy.io.loadmat('Xtest.mat')["Xtest"]
Ytest = scipy.io.loadmat('Ytest.mat')["Ytest"]
learn(Xtest,Xtrain,Ytest,Ytrain,5) #this lowers the dimension from 256*256 to 5

def learn(testX,trainX,testY,trainY,n):
    pcmat = PCA(trainX,n)
    lowdimtrain=mat(trainX)*pcmat #lower the dimension of trainX
    lowdimtest=mat(testX)*pcmat #lower the dimension of testX
    #run some learning algorithm here using the low dimension matrices for example
    trainset = []    

    knnres = KNN(lowdimtrain, trainY, lowdimtest ,k)
    numloss=0
    for i in range(len(knnres)):
        if knnres[i]!=testY[i]:
            numloss+=1
    return numloss

def PCA(Xparam, n):
    X = mat(Xparam)
    Xtranspose = X.transpose()
    A=Xtranspose*X
    return eigs(A,n)

def eigs(M,k):
    [vals,vecs]=LA.eig(M)
    return LM2ML(vecs[:k])

def LM2ML(lm):
    U=[[]]
    temp = []
    for i in lm: 
       for j in range(size(i)):
           temp.append(i[0,j])
       U.append(temp)
       temp = []
    U=U[1:]
    return U

为了对图像进行分类,您可以使用k近邻。即你找到k个最近的图像,并通过对k个最近的图像的多数投票来标记你的图像。例如:

def KNN(trainset, Ytrainvec, testset, k):
    eucdist = scidist.cdist(testset,trainset,'sqeuclidean')
    res=[]
    for dists in eucdist:
        distup = zip(dists, Ytrainvec)
        minVals = []
    sumLabel=0;
    for it in range(k):
        minIndex = index_min(dists)
        (minVal,minLabel) = distup[minIndex]
        del distup[minIndex]
        dists=numpy.delete(dists,minIndex,0)
        if minLabel == 1:
            sumLabel+=1
        else:
            sumLabel-=1
        if(sumLabel>0):
            res.append(1)
        else:
            res.append(0)
    return res

答案 1 :(得分:3)

我知道我没有直接回答你的问题。但是图像变化很大:遥感,物体,场景,功能磁共振成像,生物医学,面部等......如果你缩小分类范围并让我们知道,这将有所帮助。

你在计算什么描述符?我使用的大多数代码(以及计算机视觉社区)都在MATLAB中,而不是在python中,但我确信有类似的代码可用(pycv模块& http://www.pythonware.com/products/pil/)。尝试使用麻省理工学院人员预先编译的最先进代码的描述符基准测试:http://people.csail.mit.edu/jxiao/SUN/尝试查看GIST,HOG和SIFT,这些是非常标准的,具体取决于您想要分析的内容:场景,对象或点分别。

答案 2 :(得分:0)

首先,导入库并提取图片

from sklearn import datasets    
%matplotlib inline
import sklearn as sk
import numpy as np
import matplotlib.pyplot as plt
digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target
ind4 = np.where(y_digits==4)
ind5=  np.where(y_digits==5)
plt.imshow(X_digits[1778].reshape((8,8)),cmap=plt.cm.gray_r)

答案 3 :(得分:0)

然后使用此功能:

xx = np.arange(64)

def feature_11(xx):

yy=xx.reshape(8,8)
feature_1 = sum(yy[0:2,:])
feature11 = sum(feature_1)
print (feature11)
return feature11

feature_11(X_digits [1778])

然后使用lda:

来自sklearn.discriminant_analysis import LinearDiscriminantAnalysis

clf = LinearDiscriminantAnalysis()

ind_all = np.arange(0,len(y_digits))

np.random.shuffle(ind_all)

ind_training = ind_all [0:int(0.8 * len(ind_all))]

ind_test = ind_all [int(0.8 * len(ind_all)):]

clf.fit(X_digits [ind_training],y_digits [ind_training])

y_predicted = clf.predict(X_digits [ind_test])

plt.subplot(211)

plt.stem(y_predicted)

plt.subplot(212)

plt.stem(y_digits [ind_test],'r')

plt.stem(y_digits [ind_test] - y_predicted,'r')

总和(y_predicted == y_digits [ind_test])/ len(y_predicted)