def naiveBayes(trainingData, trainingClasses, testData, testClasses):
    nbClassifier = cv2.NormalBayesClassifier()
    nbClassifier.train(trainingData, trainingClasses)
    ret, results = nbClassifier.predict(testData)
    print results
    return calculateAccuracy(testClasses,
                             results), calcSensitivity(testClasses, results)
Beispiel #2
0
def CallNaiveBayes(trainData, trainLabels, testData):

    ## Create a Naive (normal) Bayes Classifier
    classifier = cv2.NormalBayesClassifier()
    classifier.train(trainData, trainLabels)

    ## Use classifier to predict the test data
    ## TODO: (Overwrite the following line with your answer.)
    retval, predictions = classifier.predict(testData)
    #predictions = np.zeros((testData.shape[0], 1), np.float32)

    return predictions
Beispiel #3
0
def supervised_classification_opencv(input_band_list,sample_matrix,train_matrix,classification_type):
    
    '''Supervised classification using OpenCV library
    
    Function used to recall the supervised classification from the OpenCV library. Train and samples matrix can be extracted directly from a shapefile with the generate_training function
    or from a text file.
    Available algorithms: Support Vector Machine, Decision Tree, Gradient Boosted Tree, Normal Bayes, Random Forest, K-Nearest-Neighbors.

    Example: supervised_classification_opencv(input_band_list=(band1,band2,band3,band4),sample_matrix=samples_mat,train_matrix=training_mat,classification_type='svm')

    :param input_band_list: list of 2darrays corresponding to bands (band 1: blue) (list of numpy arrays)
    :param sample_matrix: 2darray with the samples to add 
    :param train_matrix: 1darray with the corresponding classes
    :param classification type: definition of the desired classification algorithm ('svm','dt','gbt','bayes','rf','knn') (string)
    :returns:  2darray with predicted classes
    :raises: AttributeError, KeyError
    
    Author: Daniele De Vecchi - Daniel Aurelio Galeazzo - Mostapha Harb
    Last modified: 01/04/2014
    '''
    
    stack_new = np.dstack((input_band_list[0],input_band_list[1],input_band_list[2],input_band_list[3])) #stack with the original bands
    samples = stack_new.reshape((-1,4)) #input image as matrix with rows = (rows_original * cols_original) and columns = number of bands
    print classification_type
    
    if classification_type == "svm":
    
        params = dict( kernel_type = cv2.SVM_LINEAR, svm_type = cv2.SVM_C_SVC,C = 10000 ) #definition of the SVM parameters (kernel, type of algorithm and parameter related to the chosen algorithm
        cl = cv2.SVM()
        cl.train_auto(sample_matrix,train_matrix,None,None,params,100) #creation of the training set forcing the parameters optimization
        y_val = cl.predict_all(samples) #classification of the input image
        output = y_val.reshape(input_band_list[0].shape).astype(np.uint16) #reshape to the original rows and columns
    
    if classification_type == "dt":
        
        cl = tree.DecisionTreeClassifier()
        cl = cl.fit(sample_matrix, train_matrix)
        y_val = cl.predict(samples)
        output = y_val.reshape(input_band_list[0].shape).astype(np.uint16)
    
    if classification_type == "gbt":
        
        cl = GradientBoostingClassifier()
        cl = cl.fit(sample_matrix, train_matrix)
        y_val = cl.predict(samples)
        output = y_val.reshape(input_band_list[0].shape).astype(np.uint16)
    
    if classification_type == "bayes":
    
        cl = cv2.NormalBayesClassifier(sample_matrix, train_matrix)
        y_val = cl.predict(samples)
        y_val = np.array(y_val[1])
        output = y_val.reshape(input_band_list[0].shape).astype(np.uint16)
        
    if classification_type == "rf":
        
        cl = cv2.RTrees()
        cl.train(sample_matrix, cv2.CV_ROW_SAMPLE, train_matrix)
        y_val = np.float32( [cl.predict(s) for s in samples] )
        output = y_val.reshape(input_band_list[0].shape).astype(np.uint16)
        
    if classification_type == "knn":
        
        cl = cv2.KNearest()
        cl.train(sample_matrix, train_matrix)
        retval, results, neigh_resp, dists = cl.find_nearest(samples, k = 10)
        y_val = results.ravel()
        output = y_val.reshape(input_band_list[0].shape).astype(np.uint16)
    
    return output
class NormalBayesClassifier(AbstractClassifier):
    classifier = cv2.NormalBayesClassifier()

    def predict(self, sample):
        return self.classifier.predict(np.matrix(sample))[0]
Beispiel #5
0
print "Perform K-Means Training..."
for (i, fvec) in enumerate(fvec_train):
    print "Image: " + str(i)
    ret, labels, centers = cv2.kmeans(fvec, K_TRAIN, criteria, K_ATTEMPTS,
                                      cv2.KMEANS_RANDOM_CENTERS)  #Get K-Means
    #Reshape and save labels
    labels = labels.flatten()
    labels = labels.reshape((img_train[i].shape[0], img_train[i].shape[1]))
    kmean_train.append(labels)
    #Save centers for use during training
    for c in centers:
        center_train.append(c)

# CREATE MODEL
if DO_BAYES:
    bayes_model = cv2.NormalBayesClassifier()
else:
    rtrees_model = cv2.RTrees()

# PREPARE FOR CLASSIFICATION (CHECK FOR 50% OVERLAP)
for i in range(len(kmean_train)):
    # Count how many of each cluster are in image
    region_count = [0] * K_TRAIN
    overlap_count = [0] * K_TRAIN
    for x in range(kmean_train[i].shape[0]):
        for y in range(kmean_train[i].shape[1]):
            region_count[kmean_train[i][x, y]] += 1
            if img_train_gt[i][x, y] == 255:
                overlap_count[kmean_train[i][x, y]] += 1

    #Check Strength of match ratio:
def naiveBayes(trainingData, trainingClasses, testData, testClasses):
    nbClassifier = cv2.NormalBayesClassifier()
    nbClassifier.train(trainingData, trainingClasses)
    ret, results = nbClassifier.predict(testData)
    return results