forked from facebookresearch/ImageNet-Adversarial-Training
-
Notifications
You must be signed in to change notification settings - Fork 1
/
inference-example.py
executable file
·51 lines (40 loc) · 1.57 KB
/
inference-example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import numpy as np
import cv2
import tensorflow as tf
from tensorpack import TowerContext
from tensorpack.tfutils import get_model_loader
import nets
"""
A small inference example for attackers to play with.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--depth', help='ResNet depth',
type=int, default=152, choices=[50, 101, 152])
parser.add_argument('--arch', help='Name of architectures defined in nets.py',
default='ResNetDenoise')
parser.add_argument('--load', help='path to checkpoint')
parser.add_argument('--input', help='path to input image')
args = parser.parse_args()
model = getattr(nets, args.arch + 'Model')(args)
input = tf.placeholder(tf.float32, shape=(None, 224, 224, 3))
image = input / 127.5 - 1.0
image = tf.transpose(image, [0, 3, 1, 2])
with TowerContext('', is_training=False):
logits = model.get_logits(image)
sess = tf.Session()
get_model_loader(args.load).init(sess)
sample = cv2.imread(args.input) # this is a BGR image, not RGB
# imagenet evaluation uses standard imagenet pre-processing
# (resize shortest edge to 256 + center crop 224).
# However, for images of unknown sources, let's just do a naive resize.
sample = cv2.resize(sample, (224, 224))
l = sess.run(logits, feed_dict={input: np.array([sample])})
print("Prediction: ", l.argmax())