使用Python和OpenCV的局部二值模式

我使用二值模式创建了一个机器学习项目,通过图像中的Haralick纹理来检测植物疾病。我使用了5组不同的数据进行训练,预测准确率为60%。现在我遇到一个情况,需要在一张图片上打印出3种可能的疾病。例如,我上传了一张图片,预测结果是“螨虫”,并且还想检查图片中是否有其他3种可能的植物疾病。

如何使用Python的局部二值模式来实现这3种可能的疾病预测?

image

我尝试的完整代码如下:

import cv2import numpy as npimport osimport globimport mahotas as mtfrom sklearn.svm import LinearSVCfrom sklearn.metrics import mean_squared_errorimport joblib# function to extract haralick textures from an imagedef 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_meandef 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 datasettrain_path  = "D:/ai training/aphids/Anothertest"train_names = os.listdir(train_path)# empty list to hold feature vectors and train labelstrain_features = []train_labels   = []# loop over the training datasetprint ("[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 modelif 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 imagestest_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)

回答:

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注