程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Mask rcnn批量预测自己的测试集图像,去除白边保存和测试集实际大小的数据图像(以DWTT断口预测实验为例)

发布于2019-12-07 10:01     阅读(3447)     评论(0)     点赞(10)     收藏(3)


1.批量预测自己的数据集图像--修改test.py文件

  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. import random
  5. import math
  6. import numpy as np
  7. import skimage.io
  8. import matplotlib
  9. matplotlib.use('TkAgg')
  10. import matplotlib.pyplot as plt
  11. import cv2
  12. import time
  13. from mrcnn.config import Config
  14. from datetime import datetime
  15. # Root directory of the project
  16. ROOT_DIR = os.getcwd()
  17. # Import Mask RCNN
  18. sys.path.append(ROOT_DIR) # To find local version of the library
  19. from mrcnn import utils
  20. import mrcnn.model as modellib
  21. from mrcnn import visualize
  22. # Directory to save logs and trained model
  23. MODEL_DIR = os.path.join(ROOT_DIR, "logs")
  24. # Local path to trained weights file
  25. M_DIR = os.path.abspath("E:/graduation/Mask_RCNN-master/Mask_RCNN-master/maskrcnn_fragility/maskrcnn_fragility/logs/shapes20190604T2347/")
  26. COCO_MODEL_PATH = os.path.join(M_DIR,"mask_rcnn_shapes_0015.h5")
  27. # Download COCO trained weights from Releases if needed
  28. if not os.path.exists(COCO_MODEL_PATH):
  29. utils.download_trained_weights(COCO_MODEL_PATH)
  30. print("cuiwei***********************")
  31. # Directory of images to run detection on
  32. IMAGE_DIR = os.path.join(ROOT_DIR, "images")
  33. class ShapesConfig(Config):
  34. """Configuration for training on the toy shapes dataset.
  35. Derives from the base Config class and overrides values specific
  36. to the toy shapes dataset.
  37. """
  38. # Give the configuration a recognizable name
  39. NAME = "fragility"
  40. # Train on 1 GPU and 8 images per GPU. We can put multiple images on each
  41. # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
  42. GPU_COUNT = 1
  43. IMAGES_PER_GPU = 1
  44. # Number of classes (including background)
  45. NUM_CLASSES = 1 + 1 # background + 3 shapes
  46. # Use small images for faster training. Set the limits of the small side
  47. # the large side, and that determines the image shape.
  48. IMAGE_MIN_DIM = 256
  49. IMAGE_MAX_DIM = 512
  50. # Use smaller anchors because our image and objects are small
  51. RPN_ANCHOR_SCALES = (8 * 6, 16 * 6, 32 * 6, 64 * 6, 128 * 6) # anchor side in pixels
  52. # Reduce training ROIs per image because the images are small and have
  53. # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
  54. TRAIN_ROIS_PER_IMAGE =100
  55. # Use a small epoch since the data is simple
  56. STEPS_PER_EPOCH = 100
  57. # use small validation steps since the epoch is small
  58. VALIDATION_STEPS = 50
  59. #import train_tongue
  60. class InferenceConfig(ShapesConfig):
  61. # Set batch size to 1 since we'll be running inference on
  62. # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
  63. GPU_COUNT = 1
  64. IMAGES_PER_GPU = 1
  65. config = InferenceConfig()
  66. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
  67. # Create model object in inference mode.
  68. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
  69. # Load weights trained on MS-COCO
  70. model.load_weights(COCO_MODEL_PATH, by_name=True)
  71. # COCO Class names
  72. # Index of the class in the list is its ID. For example, to get ID of
  73. # the teddy bear class, use: class_names.index('teddy bear')
  74. class_names = ['BG', 'fragility']
  75. # Load a random image from the images folder
  76. file_names = next(os.walk(IMAGE_DIR))[2]
  77. image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
  78. #image = skimage.io.imread(os.path.abspath(IMAGE_DIR))
  79. #####################################################################批量图像预测
  80. count = os.listdir(IMAGE_DIR)
  81. for i in range(0,len(count)):
  82. path = os.path.join(IMAGE_DIR, count[i])
  83. if os.path.isfile(path):
  84. file_names = next(os.walk(IMAGE_DIR))[2]
  85. image = skimage.io.imread(os.path.join(IMAGE_DIR, count[i]))
  86. # Run detection
  87. results = model.detect([image], verbose=1)
  88. r = results[0]
  89. visualize.display_instances(count[i],image, r['rois'], r['masks'], r['class_ids'],
  90. class_names, r['scores'])
  91. #####################################################################批量图像预测

主要修改部分主要集中在最后注释部分的批量图像预测。

2.去除白边保存和测试集实际大小的数据图像-

1)  修改visualize.py文件

  1. def display_instances(count,image, boxes, masks, class_ids, class_names,
  2. scores=None, title="",
  3. figsize=(16, 16), ax=None,
  4. #figsize=(2.56, 5.12), ax=None,
  5. show_mask=True, show_bbox=True,
  6. colors=None, captions=None):

2)  在函数display_instance()的定义中增加一个参数count,此参数和test.py文件中的count[i]参数相对应。为后续的保存文件命名作准备。

  1. #ax.set_ylim(height + 10, -10) #显示图像的外围边框,保存原始图像大小的数据时需要注释掉
  2. #ax.set_xlim(-10, width + 10)
  3. ax.axis('off') #关闭坐标轴

对这一部分需要进行注释修改。

3)  对if auto_show:部分进行的修改

  1. if auto_show:
  2. ###############保存预测结果图像
  3. fig = plt.gcf()
  4. fig.set_size_inches(width / 100.0, height / 100.0) # 输出原始图像width*height的像素
  5. plt.gca().xaxis.set_major_locator(plt.NullLocator())
  6. plt.gca().yaxis.set_major_locator(plt.NullLocator())
  7. plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
  8. plt.margins(0, 0)
  9. plt.savefig("E:/graduation/Mask_RCNN-master/Mask_RCNN-master/maskrcnn_fragility/maskrcnn_fragility/test_results/%3s.jpg" % (str(count[7:10])),pad_inches=0.0) #使用原始图像名字的第7到第9个字符来命名新的图像
  10. ###############保存预测结果图像
  11. #plt.show() #在保存预测结果图像时,如果不想没保存一张显示一次,可以把
  12. # 他注释掉。

修改完以上各个部分以后就可以进行批量的对自己测试集中的图像进行预测,并以测试集图像大小的像素值将图像进行保存。

其中测试集中的图像如下所示:

进行预测后保存的结果图像如下所示。 

数据集的实际大小时256*512的。



所属网站分类: 技术文章 > 博客

作者:

链接:https://www.pythonheidong.com/blog/article/169891/7d1fb9708a5a512e8dad/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

10 1
收藏该文
已收藏

评论内容:(最多支持255个字符)