MCPcopy Create free account
hub / github.com/Sirwenhao/Deep-Learning-Notes / main

Function main

CV/Pytorch_classification/ResNet/batch_predict.py:12–68  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

10from model import resnet34
11
12def main():
13 device = torch.device("cuda:0" if torch.cuda.is_available() else 'cpu')
14
15 data_transform = transforms.Compose(
16 [transforms.Resize(256),
17 transforms.CenterCrop(224),
18 transforms.ToTensor(),
19 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
20
21 #load image
22 # 给定需要进行批量测试的图像文件夹路径
23 imgs_root = '/Users/WH/Desktop/pytorch_classification/flower_imgs'
24 assert os.path.exists(imgs_root), f"file: '{imgs_root}' does not exist."
25 # 读取指定文件夹下所有的jpg文件
26 img_path_list = [os.path.join(imgs_root, i) for i in os.listdir(imgs_root) if i.endswith(".jpg") or i.endswith(".jpeg")]
27 # print("img_path_list", img_path_list)
28
29 # read class_dict
30 json_path = '/Users/WH/Desktop/Deep-Learning-for-image-processing/data_set/class_indices.json'
31 assert os.path.exists(json_path), f"file: {json_path} does not exist."
32
33
34 json_file = open(json_path, 'r')
35 class_indict = json.load(json_file)
36
37 # create model
38 model = resnet34(num_classes=5).to(device)
39
40 # load model weights
41 weights_path = '/Users/WH/Desktop/Deep-Learning-for-image-processing/Pytorch_classification/ResNet/ResNet34_retrain.pth'
42 assert os.path.exists(weights_path), f"file: {weights_path} does not exits."
43 model.load_state_dict(torch.load(weights_path, map_location=device))
44
45 # prediction
46 model.eval() # model.eval()将模型设置为inference模式,1、关闭BN和Dropout的影响;2、关闭梯度计算
47 batch_size = 6 # 每次进行预测时打包的图片数量
48 with torch.no_grad():
49 for ids in range(0, len(img_path_list) // batch_size):
50 img_list = []
51 for img_path in img_path_list[ids * batch_size: (ids+1)*batch_size]:
52 assert os.path.exists(img_path), f"file: '{img_path}' does not exist."
53 img = Image.open(img_path)
54 img = data_transform(img)
55 img_list.append(img)
56
57 # batch img
58 # 将img_list列表中的所有图像打包成一个batch
59 batch_img = torch.stack(img_list, dim=0)
60 # predict class
61 output = model(batch_img.to(device)).cpu()
62 predict = torch.softmax(output, dim=1)
63 probs, classes = torch.max(predict, dim=1)
64
65 for idx, (pro, cla) in enumerate(zip(probs, classes)):
66 print("image: {} class: {} prob: {:.3}".format(img_path_list[ids * batch_size + idx],
67 class_indict[str(cla.numpy())],
68 pro.numpy()))
69if __name__ == '__main__':

Callers 1

batch_predict.pyFile · 0.70

Calls 1

resnet34Function · 0.90

Tested by

no test coverage detected