PeterYoung777/EfficientNetV2-For-Flower-Detection
0
1import os2import json3 4import torch5from PIL import Image6from torchvision import transforms7import matplotlib.pyplot as plt8 9from model import efficientnetv2_m as create_model10 11 12def main():13 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")14 15 img_size = {"s": [300, 384], # train_size, val_size16 "m": [384, 480],17 "l": [384, 480]}18 num_model = "s"19 20 data_transform = transforms.Compose(21 [transforms.Resize(img_size[num_model][1]),22 transforms.CenterCrop(img_size[num_model][1]),23 transforms.ToTensor(),24 transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])25 26 # load image27 img_path = "../d.jpg"28 assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path)29 img = Image.open(img_path)30 plt.imshow(img)31 # [N, C, H, W]32 img = data_transform(img)33 # expand batch dimension34 img = torch.unsqueeze(img, dim=0)35 36 # read class_indict37 json_path = './class_indices.json'38 assert os.path.exists(json_path), "file: '{}' dose not exist.".format(json_path)39 40 json_file = open(json_path, "r")41 class_indict = json.load(json_file)42 43 # create model44 model = create_model(num_classes=5).to(device)45 # load model weights46 model_weight_path = "./weights/model-20.pth"47 model.load_state_dict(torch.load(model_weight_path, map_location=device))48 model.eval()49 with torch.no_grad():50 # predict class51 output = torch.squeeze(model(img.to(device))).cpu()52 predict = torch.softmax(output, dim=0)53 predict_cla = torch.argmax(predict).numpy()54 55 print_res = "class: {} prob: {:.3}".format(class_indict[str(predict_cla)],56 predict[predict_cla].numpy())57 plt.title(print_res)58 for i in range(len(predict)):59 print("class: {:10} prob: {:.3}".format(class_indict[str(i)],60 predict[i].numpy()))61 plt.show()62 63 64if __name__ == '__main__':65 main()66 