retinanet+keras训练自己数据集踩的坑

1.训练好模型后,运行训练代码,报错:ValueError: not enough values to unpack (expected 3, got 2)
网上查回复都是opencv的版本问题。
当期时间2020年1月8日09:36:30,我使用的版本为:
opencv-contrib-python 4.1.2.30
opencv-python 4.1.2.30
解决方法:
和版本无关.
在原git连接中Keras RetinaNet也有描述。
原理:需要把训练好的模型转化为inference模型
代码:在这里插入代码片

# Running directly from the repository:
keras_retinanet/bin/convert_model.py /path/to/training/model.h5 /path/to/save/inference/model.h5
# Using the installed script:
retinanet-convert-model /path/to/training/model.h5 /path/to/save/inference/model.h5

当然,我个人觉得这种方式,太过于复杂。
下面附上个人使用的modeltest.py

import keras
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
from keras_retinanet.utils.visualization import draw_box, draw_caption
from keras_retinanet.utils.colors import label_color

import matplotlib.pyplot as plt
import cv2
import os

#是否使用gpu
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import numpy as np
import time

import tensorflow as tf


def get_session():
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    return tf.Session(config=config)


# 设置tensorflow session 为Keras 后端
keras.backend.tensorflow_backend.set_session(get_session())
# 转化后的推断模型地址
# model_path = os.path.join('..', 'snapshots', 'predict.h5')
model_path = 'E:\\winebottle\\keras-retinanet-master\\keras_retinanet\\bin\\snapshots1\\resnet50_csv_19.h5'
# 加载模型
model = models.load_model(model_path, backbone_name='resnet50')
#解决ValueError: not enough values to unpack (expected 3, got 2)
model = models.convert_model(model)
# 建立ID与类别映射字典
labels_to_names = {  0:‘类别1’}
# 加载需要检测的图片
path = '/home/zbb/keras-retinanet/CSV/test/50.JPG'

save_path = '保存的路径'
image_names = sorted(os.listdir(path))
for image_path in image_names:
    image = read_image_bgr(path + image_path)
    print(path + image_path)
    # copy到另一个对象并转为RGB文件
    draw = image.copy()
    draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)
    # 图像预处理
    image = preprocess_image(image)
    image, scale = resize_image(image)
    # 模型预测
    start = time.time()


    boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0))
    print("processing time: ", time.time() - start)

    # 矫正比例
    boxes /= scale
    # 目标检测可视化展示
    for box, score, label in zip(boxes[0], scores[0], labels[0]):
        # 设置预测得分最低阈值
        if score < 0.75:
            break
        color = label_color(label)
        print(color)
        b = box.astype(int)
        draw_box(draw, b, color=color)
        caption = "{} {:.3f}".format(labels_to_names[label], score)
        draw_caption(draw, b, caption)
    # 图片展示
    plt.figure(figsize=(15, 15))
    plt.axis('off')
    plt.imshow(draw)
    plt.savefig(save_path + image_path, format='JPG', transparent=True, pad_inches=0, dpi=300, bbox_inches='tight')


发布了29 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33083551/article/details/103885590
今日推荐