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')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章