Advertisement
Guest User

Untitled

a guest
Apr 1st, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. from sklearn.naive_bayes import GaussianNB
  2. from PIL import Image
  3. from imutils import paths
  4. import numpy as np
  5. import argparse
  6. import os
  7.  
  8. def extract_color_stats(image):
  9.     # split the input image into its respective RGB color channels
  10.     # and then create a feature vector with 6 values: the mean and
  11.     # standard deviation for each of the 3 channels, respectively
  12.     (R, G, B) = image.split()
  13.     features = [np.mean(R), np.mean(G), np.mean(B), np.std(R),
  14.         np.std(G), np.std(B)]
  15.  
  16.     # return our set of features
  17.     return features
  18.  
  19. # construct the argument parser and parse the arguments
  20. ap = argparse.ArgumentParser()
  21. ap.add_argument("-d", "--dataset", type=str, default="3scenes",
  22.     help="path to directory containing the '3scenes' dataset")
  23. args = vars(ap.parse_args())
  24.  
  25. # grab all image paths in the input dataset directory, initialize our
  26. # list of extracted features and corresponding labels
  27. print("[INFO] extracting image features...")
  28. imagePaths = paths.list_images(args["dataset"])
  29. data = []
  30. labels = []
  31.  
  32. # loop over our input images
  33. for imagePath in imagePaths:
  34.     # load the input image from disk, compute color channel
  35.     # statistics, and then update our data list
  36.     image = Image.open(imagePath)
  37.     features = extract_color_stats(image)
  38.     data.append(features)
  39.  
  40.     # extract the class label from the file path and update the
  41.     # labels list
  42.     label = imagePath.split(os.path.sep)[-2]
  43.     labels.append(label)
  44.  
  45. # encode the labels, converting them from strings to integers
  46. le = LabelEncoder()
  47. labels = le.fit_transform(labels)
  48.  
  49. # perform a training and testing split, using 75% of the data for
  50. # training and 25% for evaluation
  51. (trainX, testX, trainY, testY) = train_test_split(data, labels,
  52.     test_size=0.25)
  53.  
  54. # train the model
  55. print("[INFO] using Gaussian model")
  56. model = GaussianNB()
  57. model.fit(trainX, trainY)
  58.  
  59. # make predictions on our data and show a classification report
  60. print("[INFO] evaluating...")
  61. predictions = model.predict(testX)
  62. print(classification_report(testY, predictions,
  63.     target_names=le.classes_))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement