当前位置:   article > 正文

基于Python的水果分类训练代码和识别代码和gui界面(支持VGG16,googlenet, resnet, inception, mobilenet)_图像识别水果 python

图像识别水果 python

基于Python的水果分类训练代码和识别代码和gui界面(支持VGG16,googlenet, resnet, inception, mobilenet)

设计项目代码案例地址,一对一指导设计,疑难解答,代码安装部署:咨询链接 问题

有一组水果的训练集,我们对模型进行训练,思路跟之前我们识别猫与狗一样。
设计解决这个问题的思路
1、下载与放置训练图片
2、现在对应的依赖,tensorflow、numpy等等
3、构建训练集合
4、建模
5、对模型进行训练
6、用测试模型进行验证
7、输出结果
8、优化模型 to step4
[1] 图片地址
https://www.kaggle.com/moltean/fruits 现在数据,现在速度比较慢,可以使用网盘。
网盘地址(提取码:a9wr)
【2】处理训练集的数据结构

      
      
  1. import os
  2. import pandas as pd
  3. train_dir = './Training/'
  4. test_dir = './Test/'
  5. fruits = []
  6. fruits_image = []
  7. for i in os.listdir(train_dir):
  8.      for image_filename in os.listdir(train_dir + i):
  9.         fruits.append(i) # name of the fruit
  10.         fruits_image.append(i + '/' + image_filename)
  11. train_fruits = pd.DataFrame(fruits, columns=[ "Fruits"])
  12. train_fruits[ "Fruits Image"] = fruits_image
  • 1
结果输出

       
       
  1.            Fruits              Fruits Image
  2. 0        Tomato 4    Tomato 4 /r_ 236_ 100.jpg
  3. 1        Tomato 4      Tomato 4 / 247_ 100.jpg
  4. 2        Tomato 4      Tomato 4 / 257_ 100.jpg
  5. 3        Tomato 4     Tomato 4 /r_ 78_ 100.jpg
  6. 4        Tomato 4     Tomato 4 /r_ 68_ 100.jpg
  7. ...           ...                       ...
  8. 67687  Peach Flat    Peach Flat / 220_ 100.jpg
  9. 67688  Peach Flat  Peach Flat /r_ 127_ 100.jpg
  10. 67689  Peach Flat    Peach Flat / 156_ 100.jpg
  11. 67690  Peach Flat  Peach Flat /r_ 137_ 100.jpg
  12. 67691  Peach Flat    Peach Flat / 146_ 100.jpg
  • 1
【3】构造模型

        
        
  1. import matplotlib.pyplot as plt
  2. import seaborn as sns
  3. from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
  4. from glob import glob
  5. from keras.models import Sequential
  6. from keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense
  7. img = load_img(train_dir + "Cantaloupe 1/r_234_100.jpg")
  8. plt.imshow(img)
  9. plt.axis( "off")
  10. plt.show()
  11. array_image = img_to_array(img)
  12. # shape (100,100)
  13. print( "Image Shape --> ", array_image.shape)
  14. # 131个类目
  15. fruitCountUnique = glob(train_dir + '/*' )
  16. numberOfClass = len(fruitCountUnique)
  17. print( "How many different fruits are there --> ",numberOfClass)
  18. # 构建模型
  19. model = Sequential()
  20. model.add(Conv2D( 32,( 3, 3),input_shape = array_image.shape))
  21. model.add(Activation( "relu"))
  22. model.add(MaxPooling2D())
  23. model.add(Conv2D( 32,( 3, 3)))
  24. model.add(Activation( "relu"))
  25. model.add(MaxPooling2D())
  26. model.add(Conv2D( 64,( 3, 3)))
  27. model.add(Activation( "relu"))
  28. model.add(MaxPooling2D())
  29. model.add(Flatten())
  30. model.add(Dense( 1024))
  31. model.add(Activation( "relu"))
  32. model.add(Dropout( 0.5))
  33. # 区分131类
  34. model.add(Dense(numberOfClass)) # output
  35. model.add(Activation( "softmax"))
  36. model. compile(loss = "categorical_crossentropy",
  37.               optimizer = "rmsprop",
  38.               metrics = [ "accuracy"])
  39. print( "Target Size --> ", array_image.shape[: 2])
  • 1

【4】训练模型

        
        
  1. train_datagen = ImageDataGenerator(rescale= 1./ 255,
  2.                                    shear_range = 0.3,
  3.                                    horizontal_flip= True,
  4.                                    zoom_range = 0.3)
  5. test_datagen = ImageDataGenerator(rescale= 1./ 255)
  6. epochs = 100
  7. batch_size = 32
  8. train_generator = train_datagen.flow_from_directory(
  9.                 train_dir,
  10.                 target_size= array_image.shape[: 2],
  11.                 batch_size = batch_size,
  12.                 color_mode= "rgb",
  13.                 class_mode= "categorical")
  14. test_generator = test_datagen.flow_from_directory(
  15.                 test_dir,
  16.                 target_size= array_image.shape[: 2],
  17.                 batch_size = batch_size,
  18.                 color_mode= "rgb",
  19.                 class_mode= "categorical")
  20. for data_batch, labels_batch in train_generator:
  21.      print( "data_batch shape --> ",data_batch.shape)
  22.      print( "labels_batch shape --> ",labels_batch.shape)
  23.      break
  24. hist = model.fit_generator(
  25.         generator = train_generator,
  26.         steps_per_epoch = 1600 // batch_size,
  27.         epochs=epochs,
  28.         validation_data = test_generator,
  29.         validation_steps = 800 // batch_size)
  30. #保存模型 model_fruits.h5
  31. model.save( 'model_fruits.h5')
  • 1

【5】展示训练结果

         
         
  1. #展示损失模型结果
  2. plt.figure()
  3. plt.plot(hist.history[ "loss"],label = "Train Loss", color = "black")
  4. plt.plot(hist.history[ "val_loss"],label = "Validation Loss", color = "darkred", linestyle= "dashed",markeredgecolor = "purple", markeredgewidth = 2)
  5. plt.title( "Model Loss", color = "darkred", size = 13)
  6. plt.legend()
  7. plt.show()
  8. #展示精确模型结果
  9. plt.figure()
  10. plt.plot(hist.history[ "accuracy"],label = "Train Accuracy", color = "black")
  11. plt.plot(hist.history[ "val_accuracy"],label = "Validation Accuracy", color = "darkred", linestyle= "dashed",markeredgecolor = "purple", markeredgewidth = 2)
  12. plt.title( "Model Accuracy", color = "darkred", size = 13)
  13. plt.legend()
  14. plt.show()
  • 1

验证
新建一个文件,用于验证训练出来的模型

      
      
  1. from tensorflow.keras.models import load_model
  2. import os
  3. import pandas as pd
  4. from keras.preprocessing.image import ImageDataGenerator,img_to_array, load_img
  5. import cv2,matplotlib.pyplot as plt,numpy as np
  6. from keras.preprocessing import image
  7. train_datagen = ImageDataGenerator(rescale= 1./ 255,
  8.                                     shear_range = 0.3,
  9.                                     horizontal_flip= True,
  10.                                     zoom_range = 0.3)
  11. model = load_model( 'model_fruits.h5')
  12. batch_size = 32
  13. img = load_img( "./Test/Apricot/3_100.jpg",target_size=( 100, 100))
  14. plt.imshow(img)
  15. plt.show()
  16. array_image = img_to_array(img)
  17. array_image = array_image * 1./ 255
  18. x = np.expand_dims(array_image, axis= 0)
  19. images = np.vstack([x])
  20. classes = model.predict_classes(images, batch_size= 10)
  21. print(classes)
  22. train_dir = './Training/'
  23. train_generator = train_datagen.flow_from_directory(
  24.         train_dir,
  25.         target_size= array_image.shape[: 2],
  26.         batch_size = batch_size,
  27.         color_mode= "rgb",
  28.         class_mode= "categorical”)
  29. print(train_generator.class_indices)
  • 1

输出结果


      
      
  1. [ 13]
  2. Found 67692 images belonging to 131 classes.
  3. { 'Apple Braeburn': 0, 'Apple Crimson Snow': 1, 'Apple Golden 1': 2, 'Apple Golden 2': 3, 'Apple Golden 3': 4, 'Apple Granny Smith': 5, 'Apple Pink Lady': 6, 'Apple Red 1': 7, 'Apple Red 2': 8, 'Apple Red 3': 9, 'Apple Red Delicious': 10, 'Apple Red Yellow 1': 11, 'Apple Red Yellow 2': 12, 'Apricot': 13, 'Avocado': 14, 'Avocado ripe': 15, 'Banana': 16, 'Banana Lady Finger': 17, 'Banana Red': 18, 'Beetroot': 19, 'Blueberry': 20, 'Cactus fruit': 21, 'Cantaloupe 1': 22, 'Cantaloupe 2': 23, 'Carambula': 24, 'Cauliflower': 25, 'Cherry 1': 26, 'Cherry 2': 27, 'Cherry Rainier': 28, 'Cherry Wax Black': 29, 'Cherry Wax Red': 30, 'Cherry Wax Yellow': 31, 'Chestnut': 32, 'Clementine': 33, 'Cocos': 34, 'Corn': 35, 'Corn Husk': 36, 'Cucumber Ripe': 37, 'Cucumber Ripe 2': 38, 'Dates': 39, 'Eggplant': 40, 'Fig': 41, 'Ginger Root': 42, 'Granadilla': 43, 'Grape Blue': 44, 'Grape Pink': 45, 'Grape White': 46, 'Grape White 2': 47, 'Grape White 3': 48, 'Grape White 4': 49, 'Grapefruit Pink': 50, 'Grapefruit White': 51, 'Guava': 52, 'Hazelnut': 53, 'Huckleberry': 54, 'Kaki': 55, 'Kiwi': 56, 'Kohlrabi': 57, 'Kumquats': 58, 'Lemon': 59, 'Lemon Meyer': 60, 'Limes': 61, 'Lychee': 62, 'Mandarine': 63, 'Mango': 64, 'Mango Red': 65, 'Mangostan': 66, 'Maracuja': 67, 'Melon Piel de Sapo': 68, 'Mulberry': 69, 'Nectarine': 70, 'Nectarine Flat': 71, 'Nut Forest': 72, 'Nut Pecan': 73, 'Onion Red': 74, 'Onion Red Peeled': 75, 'Onion White': 76, 'Orange': 77, 'Papaya': 78, 'Passion Fruit': 79, 'Peach': 80, 'Peach 2': 81, 'Peach Flat': 82, 'Pear': 83, 'Pear 2': 84, 'Pear Abate': 85, 'Pear Forelle': 86, 'Pear Kaiser': 87, 'Pear Monster': 88, 'Pear Red': 89, 'Pear Stone': 90, 'Pear Williams': 91, 'Pepino': 92, 'Pepper Green': 93, 'Pepper Orange': 94, 'Pepper Red': 95, 'Pepper Yellow': 96, 'Physalis': 97, 'Physalis with Husk': 98, 'Pineapple': 99, 'Pineapple Mini': 100, 'Pitahaya Red': 101, 'Plum': 102, 'Plum 2': 103, 'Plum 3': 104, 'Pomegranate': 105, 'Pomelo Sweetie': 106, 'Potato Red': 107, 'Potato Red Washed': 108, 'Potato Sweet': 109, 'Potato White': 110, 'Quince': 111, 'Rambutan': 112, 'Raspberry': 113, 'Redcurrant': 114, 'Salak': 115, 'Strawberry': 116, 'Strawberry Wedge': 117, 'Tamarillo': 118, 'Tangelo': 119, 'Tomato 1': 120, 'Tomato 2': 121, 'Tomato 3': 122, 'Tomato 4': 123, 'Tomato Cherry Red': 124, 'Tomato Heart': 125, 'Tomato Maroon': 126, 'Tomato Yellow': 127, 'Tomato not Ripened': 128, 'Walnut': 129, 'Watermelon': 130}
  • 1
识别出是13:Apricot

进一步验证


      
      
  1. fig = plt.figure(figsize=( 16, 16))
  2. axes = []
  3. files = []
  4. predictions = []
  5. true_labels = []
  6. rows = 5
  7. cols = 2
  8. # 随机选择几个图片
  9. def getRandomImage( path, img_width, img_height):
  10.      """function loads a random image from a random folder in our test path"""
  11.     folders = list( filter( lambda x: os.path.isdir(os.path.join(path, x)), os.listdir(path)))
  12.     random_directory = np.random.randint( 0, len(folders))
  13.     path_class = folders[random_directory]
  14.     file_path = os.path.join(path, path_class)
  15.     file_names = [f for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]
  16.     random_file_index = np.random.randint( 0, len(file_names))
  17.     image_name = file_names[random_file_index]
  18.     final_path = os.path.join(file_path, image_name)
  19.      return image.load_img(final_path, target_size = (img_width, img_height)), final_path, path_class
  20. def draw_test( name, pred, im, true_label):
  21.     BLACK = [ 0, 0, 0]
  22.     expanded_image = cv2.copyMakeBorder(im, 160, 0, 0, 300, cv2.BORDER_CONSTANT, value=BLACK)
  23.     cv2.putText(expanded_image, "predicted: " + pred, ( 20, 60), cv2.FONT_HERSHEY_SIMPLEX,
  24.          0.85, ( 255, 0, 0), 2)
  25.     cv2.putText(expanded_image, "true: " + true_label, ( 20, 120), cv2.FONT_HERSHEY_SIMPLEX,
  26.          0.85, ( 0, 255, 0), 2)
  27.      return expanded_image
  28. IMG_ROWS, IMG_COLS = 100, 100
  29. # predicting images
  30. for i in range( 0, 10):
  31.     path = "./Test"
  32.     img, final_path, true_label = getRandomImage(path, IMG_ROWS, IMG_COLS)
  33.     files.append(final_path)
  34.     true_labels.append(true_label)
  35.     x = image.img_to_array(img)
  36.     x = x * 1./ 255
  37.     x = np.expand_dims(x, axis= 0)
  38.     images = np.vstack([x])
  39.     classes = model.predict_classes(images, batch_size= 10)
  40.     predictions.append(classes)
  41. class_labels = train_generator.class_indices
  42. class_labels = {v: k for k, v in class_labels.items()}
  43. class_list = list(class_labels.values())
  44. for i in range( 0, len(files)):
  45.     image = cv2.imread(files[i])
  46.     image = draw_test( "Prediction", class_labels[predictions[i][ 0]], image, true_labels[i])
  47.     axes.append(fig.add_subplot(rows, cols, i+ 1))
  48.     plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
  49.     plt.grid( False)
  50.     plt.axis( 'off')
  51. plt.show()
  • 1
呈现结果

设计项目代码案例地址:咨询链接

毕业设计代做选题指导项目方向涵盖:

基于Python,MATLAB设计,OpenCV,CNN,机器学习,R-CNN,GCN,LSTM,SVM,BP神经网络,数字识别,贝叶斯,逻辑回归,卷积神经网络等算法的中文文本分类.车牌识别,知识图谱,数字图像处理,手势识别,边缘检测,图像增强,图像分类,图像分割,色彩增强,低照度。缺陷检测,病害识别,图像缺陷检测,图像去噪,去雾,去模糊,目标检测,图像分类,图像分割,语义分割等代做,代码跑通,小目标检测,网络优化,注意力机制,调参等等系
这些题目旨在涵盖深度学习图像方面的广泛应用领域,帮助本科毕业生选择适合自己兴趣和目标的毕业设计课题。学生可以根据自己的研究兴趣和可用资源来进一步调整和细化这些题目。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/642368
推荐阅读
相关标签
  

闽ICP备14008679号