预测代码中输入预处理问题

问题

在编写预测程序的时候发现一个问题,明明训练测试的时候都是可以的,在编写预测的代码的时候发现有问题,找了好久发现问题出现在图像归一化预处理问题。网络结构中如果有对模型预处理的操作的话,在编写预测代码的时候就不要进行归一化预处理操作;如果网络结构中没有对模型预处理进行操作的话,则需要进行预处理,归一化到 [ 0 , 1 ] [0, 1] [0,1] 或者 [ − 1 , 1 ] [-1, 1] [1,1]

预测程序

#!/usr/bin/env python

import os
import cv2
import sys
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input

BASE_DIR = os.path.dirname(os.path.realpath(__file__)) + '/'

class Predict(object):
    def __init__(self):
        # load model
        self.model = load_model(BASE_DIR + '../model/mbv2.h5')
        self.class_names = ['0', '1']  # init labels

    def predict(self, img_path):
        # preprocess img
        img_height, img_width = 160, 160
        img = image.load_img(img_path, target_size=(img_height, img_width))
        img = image.img_to_array(img)
        img = np.expand_dims(img, axis=0)
        # wether proprecess, if need
        # img = preprocess_input(img)
        
        # predict
        predictions = self.model.predict(img).flatten()
        predictions = tf.nn.sigmoid(predictions)
        predictions = tf.where(predictions < 0.5, 0, 1)
        return self.class_names[predictions[0]]


if __name__ == "__main__":
    img_path = sys.argv[1]
    pred = Predict()
    predict_label = pred.predict(img_path)
    print(predict_label)

参考

Guess you like

Origin blog.csdn.net/uncle_ll/article/details/121910018