【问题标题】:Local Binary Patterns with Python & OpenCV使用 Python 和 OpenCV 的本地二进制模式
【发布时间】:2021-07-03 01:00:36
【问题描述】:

我使用二进制模式制作了一个机器学习项目,使用图像中的 haralick 纹理检测植物病害,我用 5 组不同的数据对其进行了训练,它的预测准确率为 60%。现在我遇到了在一张图像上打印 3 种可能的疾病的情况。 示例我上传了一张图片并预测它有“螨虫”,还想检查植物图像中是否还有其他 3 种可能的疾病。

如何使用本地二进制模式在python中实现3个概率?

正在尝试完整代码

import cv2
import numpy as np
import os
import glob
import mahotas as mt
from sklearn.svm import LinearSVC
from sklearn.metrics import mean_squared_error
import joblib


# function to extract haralick textures from an image
def extract_features(image):
    # calculate haralick texture features for 4 types of adjacency
    textures = mt.features.haralick(image)

    # take the mean of it and return it
    ht_mean  = textures.mean(axis=0)
    return ht_mean

def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))

    return cv2.resize(image, dim, interpolation=inter)

# load the training dataset
train_path  = "D:/ai training/aphids/Anothertest"
train_names = os.listdir(train_path)

# empty list to hold feature vectors and train labels
train_features = []
train_labels   = []
# loop over the training dataset
print ("[STATUS] Started extracting haralick textures..")

for train_name in train_names:
    cur_path = train_path + "/" + train_name
    cur_label = train_name
    i = 1
    for file in glob.glob(cur_path + "/*.jpg"):
        
        print ("Processing Image - {} in {}".format(i, cur_label))
        
        # read the training image
        image = cv2.imread(file)
        resize = ResizeWithAspectRatio(image, width=1250, height=1000) # Resize by width OR
        # convert the image to grayscale
        gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)
        # extract haralick texture from the image
        features = extract_features(gray)

        # append the feature vector and label
        train_features.append(features)
        train_labels.append(cur_label)
        
        # otherwise create the model, train the model and save the model
if os.path.exists("D:/ai training/aphids/joblib_model.sav"):
    print("Loading Trained Model")
    clf_svm = joblib.load("D:/ai training/aphids/Anothertest/joblib_model.sav")
else:
        # have a look at the size of our feature vector and labels
        print ("Training features: {}".format(np.array(train_features).shape))
        print ("Training labels: {}".format(np.array(train_labels).shape))

        # create the classifier
        print ("[STATUS] Creating the classifier..")
        clf_svm = LinearSVC(random_state=9, dual=False, max_iter=1000)

        # fit the training data and labels
        print ("[STATUS] Fitting data/label to model..")
        clf_svm.fit(train_features, train_labels)

        #savemodel
        joblib_file = 'D:/ai training/aphids/joblib_model.sav'
        joblib.dump(clf_svm, joblib_file)
    
   
        
        
        
        








#epoch
#clf_svm.fit(train_features, train_labels, epochs=10, validation_data=(X_test), y_test), batch_size=64)
#clf_svm.fit(train_features, train_labels, epochs=10, validation_data=(X_test, y_test), batch_size=64)

# loop over the test images
test_path = "D:/ai training/aphids/tata"
for file in glob.glob(test_path + "/*.jpg"):
    # read the input image
    image = cv2.imread(file)
    resize = ResizeWithAspectRatio(image, width=1250, height=1000) # Resize by width OR
    # convert to grayscale
    gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)

    # extract haralick texture from the image
    features = extract_features(gray)       

    # evaluate the model and predict label
    prediction = clf_svm.predict(features.reshape(1, -1))[0]
    
    clf_svm.fit(train_features, train_labels)
     
     # show the label
    cv2.putText(resize, prediction, (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
    print ("Prediction - {}".format(prediction))
    print("Accuracy - ", clf_svm.score(train_features, train_labels))
    
    # display the output image
    cv2.namedWindow
    cv2.imshow("Test_Image", resize)
    cv2.waitKey(0)

【问题讨论】:

    标签: python python-3.x opencv machine-learning scikit-learn


    【解决方案1】:

    LinearSVC 不提供predict_proba(它将为您提供前 3 个预测类),但它提供了decision_function,它给出了与超平面的有符号距离。 (见related question

    所以,改变这部分:

    # evaluate the model and predict label
    prediction = clf_svm.predict(features.reshape(1, -1))[0]
    
    clf_svm.fit(train_features, train_labels)
     
     # show the label
    cv2.putText(resize, prediction, (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
    print ("Prediction - {}".format(prediction))
    print("Accuracy - ", clf_svm.score(train_features, train_labels))
    

    到这里:

    # evaluate the model and predict label
    top_n_classes = 3
    predictions = clf_svm.decision_function( features.reshape(1, -1)).argsort()[:,-top_n_classes:][:,::-1]
    predictions = [train_names[i] for i in predictions[0]]
    
    clf_svm.fit(train_features, train_labels)
     
    # show the label
    y_coordinate = 30
    for prediction in predictions:
      cv2.putText(resize, prediction, (10,y_coordinate), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
      y_coordinate += 30
      print("Prediction - {}".format(prediction))
    
    print("Accuracy - ", clf_svm.score(train_features, train_labels))
    

    Demo in Google Colab

    【讨论】:

    • 什么都没有改变,还是原来的结果
    • 您能打印predictions 并查看clf_svm.predict(features.reshape(1, -1)) 是否返回多个预测吗?
    • 有什么想法可以实现吗?谢谢
    • 在这个“D:/ai training/aphids/tata”中得到了3张照片,改成这个代码后只弹出一个图像,在这个代码显示该文件夹中的所有图像之前
    • 我有 3 件事要提,在这段代码现在显示错误预测之后,在这段代码之前它显示的是正确的,现在它只从文件夹中获取一张图像,但有 3 个窗口,我关闭每个窗口以获得第三个概率,如螺栓 - 螺栓 - 螺栓
    猜你喜欢
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2013-11-11
    • 1970-01-01
    • 2019-10-05
    • 2018-12-01
    相关资源
    最近更新 更多