faster rcnn resnet50模型的特征图

用我的程序代码 生成特征图




类似于这样的

1

您会吗

发下代码

好的


稍等


w我应该给您一个文件包吧  这个能传文件吗


不知道用哪几个

# 导入对应模块包
import os
import cv2
import tensorflow as tf
import numpy as np
import pandas as pd

# 导入对应的模块
from object_detect.utils import label_map_util
from object_detect.utils import visualization_utils as vis_util
from object_detect.utils import ops as utils_ops


# Path to frozen detection graph. This is the actual model that is used for the object detection.
# 训练好的pb模型文件路径
PATH_TO_FROZEN_GRAPH = 'model/export/ssd_inception/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
# 类目配置文件pbtxt文件路径
PATH_TO_LABELS = os.path.join('dataset', 'label.pbtxt')

# 类别数量(只有肿瘤一类就填1)
NUM_CLASSES = 2

# OpenCV计时函数,获取计时开始时间
start = cv2.getTickCount()

# 定义TensorFlow图 
detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')

# 加载配置文件中的类别label
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
# 类别转换
categorys = label_map_util.convert_label_map_to_categories(label_map,max_num_classes=NUM_CLASSES,use_display_name=True)
# 类别编号index
categorys_index = label_map_util.create_category_index(categorys)

# 设置GPU配置,允许动态分配GPU显存
config = tf.ConfigProto()
config.gpu_options.allow_growth = True

# 处理每一张图片的函数
def run_inference_for_single_image(image,graph):
    with graph.as_default():
        with tf.Session() as sess:
            # 获得图中所有的op
            ops =tf.get_default_graph().get_operations()
            # 获得输出op的名字
            all_tensor_names = {output.name for op in ops for output in op.outputs}
            tensor_dict = {}
            for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks']:
                tensor_name = key + ':0'
                # 如果tensor_name在all_tensor_names中
                if tensor_name in all_tensor_names:
                    # 则获取到该tensor
                    tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)
            if 'detection_masks' in tensor_dict:             
                # The following processing is only for single image     
                detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
                detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
                real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
                detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
                detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
                detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                    detection_masks, detection_boxes, image.shape[0], image.shape[1])
                detection_masks_reframed = tf.cast(
                    tf.greater(detection_masks_reframed, 0.5), tf.uint8)
                tensor_dict['detection_masks'] = tf.expand_dims(
                    detection_masks_reframed, 0)
            # 图片输入的tensor
            image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

            # 传入图片运行模型获取结果
            output_dict = sess.run(tensor_dict,
                feed_dict={image_tensor: np.expand_dims(image, 0)})

            # 所有的结果都是float32类型的,有些数据需要做数据格式转换
            # 检测到目标的数量
            output_dict['num_detections'] = int(output_dict['num_detections'][0])
            # 目标的类型
            output_dict['detection_classes']= output_dict[
                'detection_classes'][0].astype(np.uint8)
            # 预测框坐标
            output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
            # 预测框置信度
            output_dict['detection_scores'] = output_dict['detection_scores'][0]
            if 'detection_masks' in output_dict:
                output_dict['detection_masks'] = output_dict['detection_masks'][0]

        return output_dict

                
imgs_path = 'dataset/test_test/'
# os.chdir(imgs_path)
i = 1
# 存储标注的数据,图片名,置信度,ymin, xmin, ymax, xmax
marks = []
for img in os.listdir(imgs_path):
    with detection_graph.as_default():
      with tf.Session(graph=detection_graph,config=config) as sess:
        # 读取测试图片
        imageName = imgs_path + img
        # print(imageName)
        image = cv2.imread(imageName)
        #image = cv2.imread("./dataset/JPEGImages/1.jpg")
        image_np_expanded = np.expand_dims(image,axis = 0)
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        scores = detection_graph.get_tensor_by_name('detection_scores:0')
        classes = detection_graph.get_tensor_by_name('detection_classes:0')
        # #
        output_dict = run_inference_for_single_image(image,detection_graph)
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')

        (boxes,scores,classes,num_detections) = sess.run([boxes,scores,classes,\
                                    num_detections],feed_dict={image_tensor:image_np_expanded})

        vis_util.visualize_boxes_and_labels_on_image_array(
          image,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          categorys_index,
          instance_masks = output_dict.get('detection_masks'),
          min_score_thresh = 0.6,
          use_normalized_coordinates = True,
          line_thickness = 3
          )
        boxes = np.squeeze(boxes)
        scores = np.squeeze(scores)
        ymin, xmin, ymax, xmax = boxes[0]
        score = scores[0]

        # print(ymin, xmin, ymax, xmax)
        # print(score)
        mark = [img,score,ymin, xmin, ymax, xmax]
        marks.append(mark)

        # 计时结束
        end = cv2.getTickCount()
        # 计算花费时间
        use_time = (end - start) / cv2.getTickFrequency()
        print("use_time:%0.3fs" % use_time)
        # 保存结果图。cv2.imwrite只能保存在当前路径,不能指定保存位置,
        img_name = 'result' +img
        cv2.imwrite(img_name,image)
        print('已经标记好第%d张图片'%i)

        i+=1
        #image = cv2.resize(image,None,fx=0.5,fy=0.5,interpolation=cv2.INTER_LINEAR)
        # 显示结果图
        cv2.imshow("object_detection", image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

df = pd.DataFrame(data=marks, columns=['imgname','score', 'ymin', 'xmin', 'ymax', 'xmax'])
df.to_csv('marked_faster_rcnn.csv', index=False, encoding='utf-8_sig')
print("数据导出成功!")

你是想要什么结果呢


就是这样的特征可视化的图 但是不是这张 我把图片发给你吗现在

要是能实现的话 我要那个改过 的代码

谢谢您

能发一个网盘看一下吗