Пример #1
0
def identify(image):
    with tf.Graph().as_default():
        pic = pad_image(image)
        data = cut_image(pic)
        image = tf.convert_to_tensor(data)
        image = tf.expand_dims(image, -1)
        image = tf.cast(image, dtype=tf.float32)

        Finger_model = alexnet.alexNet(image, 0.5, 2, False)
        logits = Finger_model.fc_2
        moving_average_op = tf.train.ExponentialMovingAverage(
            decay=alexnet.moving_average_decay)
        variables_to_restore = moving_average_op.variables_to_restore()
        saver = tf.train.Saver(var_list=variables_to_restore)
        with tf.Session() as sess:
            checkpoint_proto = tf.train.get_checkpoint_state(
                checkpoint_dir=checkpoint_path)
            if checkpoint_proto and checkpoint_proto.model_checkpoint_path:
                saver.restore(sess, checkpoint_proto.model_checkpoint_path)
            else:
                print('checkpoint file not found!')
                return
            predict = sess.run(logits)
            predict = np.array(predict)
            """
             Vote Mechanism
            """

            Num_0 = sum(predict == 0)
            Num_1 = sum(predict == 1)
            if Num_0[0] <= Num_1[0]:
                return "Fake"
            else:
                return "Alive"
Пример #2
0
def evaluate():
    with tf.Graph().as_default() as g:

        img_batch, label_batch = preprocess.read_and_decode('test.tfrecords',
                                                            batch_size,
                                                            flag=True)  #读入测试集
        Finger_model = alexnet.alexNet(img_batch, 0.5, 2, False)
        logits = Finger_model.fc_2
        # 判断targets是否在前k个predictions里面,当k=1时等价于常规的计算正确率的方法,sess.run(predict_true_or_false)会执行符号计
        predict_true_or_false = tf.nn.in_top_k(predictions=logits,
                                               targets=label_batch,
                                               k=1)
        # 恢复moving average操作后的模型参数
        moving_average_op = tf.train.ExponentialMovingAverage(
            decay=alexnet.moving_average_decay)
        # 返回要恢复的names到Variables的映射,也即一个map映射。如果一个变量有moving average,就使用moving average变量名作为the restore
        # name, 否则就使用变量名
        variables_to_restore = moving_average_op.variables_to_restore()
        saver = tf.train.Saver(var_list=variables_to_restore)

        summary_op = tf.summary.merge_all()  # 创建序列化后的summary对象
        # 创建一个event file,用于之后写summary对象到logdir目录下的文件中
        summary_writer = tf.summary.FileWriter(logdir='./event-log-test',
                                               graph=g)
        eval_once(summary_op, summary_writer, saver, predict_true_or_false)
Пример #3
0
def train():
    with tf.Graph().as_default():  # 指定当前图为默认graph
        global_step = tf.Variable(initial_value=0, trainable=False)

        img_batch, label_batch = preprocess.read_and_decode(tfrecords,
                                                            batch_size,
                                                            flag=True)
        Finger_model = alexnet.alexNet(img_batch, 0.5, 2, True)
        logits = Finger_model.fc_2
        total_loss = alexnet.loss(logits, label_batch)  # 计算损失
        one_step_gradient_update = alexnet.one_step_train(
            total_loss, global_step)  # 返回一步梯度更新操作
        # 创建一个saver对象,用于保存参数到文件中
        saver = tf.train.Saver(var_list=tf.all_variables(
        ))  # tf.all_variables return a list of `Variable` objects
        all_summary_obj = tf.summary.merge_all(
        )  # 返回所有summary对象先merge再serialize后的的字符串类型tensor
        initiate_variables = tf.initialize_all_variables()

        with tf.Session(config=tf.ConfigProto(
                log_device_placement=False)) as sess:
            sess.run(initiate_variables)  # 变量初始化
            tf.train.start_queue_runners(sess=sess)  # 启动所有的queuerunners
            if not os.path.exists(event_log_path):
                os.makedirs(event_log_path)
            Event_writer = tf.summary.FileWriter(logdir=event_log_path,
                                                 graph=sess.graph)
            for step in range(max_iter_num):
                _, loss_value = sess.run(
                    fetches=[one_step_gradient_update, total_loss])
                assert not np.isnan(loss_value)  # 用于验证当前迭代计算出的loss_value是否合理

                if step % 100 == 0:
                    # 添加`Summary`协议缓存到事件文件中,故不能写total_loss变量到事件文件中,因为这里的total_loss为普通的tensor类型
                    print('step %d, the loss_value is %.2f' %
                          (step, loss_value))
                    all_summaries = sess.run(all_summary_obj)
                    Event_writer.add_summary(summary=all_summaries,
                                             global_step=step)
                if step % 1000 == 0 or (step + 1) == max_iter_num:
                    if not os.path.exists(checkpoint_path):
                        os.makedirs(checkpoint_path)
                    variables_save_path = os.path.join(
                        checkpoint_path,
                        'model-parameters.bin')  # 路径合并,返回合并后的字符串
                    saver.save(
                        sess, variables_save_path, global_step=step
                    )  # 把所有变量(包括moving average前后的模型参数)保存在variables_save_path路径下
                    evaluate.evaluate()
Пример #4
0
    def load_model(self):
        dropoutPro = 1
        classNum = 1000
        skip = []
        self.imgMean = np.array([104, 117, 124], np.float)
        self.x = tf.placeholder("float", [1, 227, 227, 3])
        model = alexnet.alexNet(self.x, dropoutPro, classNum, skip)
        score = model.fc3
        self.softmax = tf.nn.softmax(score)

        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
        config = tf.ConfigProto(gpu_options=gpu_options)
        self.sess = tf.Session(config=config)
        self.sess.run(tf.global_variables_initializer())
        model.loadModel(self.sess)
Пример #5
0
def main():
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

    imagePath = "./testImages"
    imageName = ["000001.jpg"]

    withPath = lambda imgName: '{}/{}'.format(imagePath, imgName)
    # testImg = dict((imgName,cv2.imread(withPath(imgName))) for imgName in imageName)
    testImg = dict(
        (imgName, Image.open(withPath(imgName))) for imgName in imageName)

    # noinspection PyUnboundLocalVariable
    if testImg.values():
        #some params
        dropoutPro = 1
        classNum = 1000
        skip = []

        imgMean = np.array([104, 117, 124], np.float)
        x = tf.placeholder("float", [1, 227, 227, 3])

        model = alexnet.alexNet(x, dropoutPro, classNum, skip)
        score = model.fc3
        softmax = tf.nn.softmax(score)

        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
        config = tf.ConfigProto(gpu_options=gpu_options)
        with tf.Session(config=config) as sess:
            sess.run(tf.global_variables_initializer())
            model.loadModel(sess)
            for key, img in testImg.items():
                #img preprocess
                # resized = cv2.resize(img.astype(np.float), (227, 227)) - imgMean
                resized = np.array(img.resize((227, 227))) - imgMean
                maxx = np.argmax(
                    sess.run(softmax,
                             feed_dict={x: resized.reshape((1, 227, 227, 3))}))
                res = caffe_classes.class_names[maxx]

                print("{}: {}\n----".format(key, res))
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
        return image

    testImg = {args.path: url2img(args.path)}

# noinspection PyUnboundLocalVariable
if testImg.values():
    # some params
    dropoutPro = 1
    classNum = 1000
    skip = []

    imgMean = np.array([104, 117, 124], np.float)
    x = tf.placeholder("float", [1, 227, 227, 3])

    model = alexnet.alexNet(x, dropoutPro, classNum, skip)
    score = model.fc3
    softmax = tf.nn.softmax(score)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        model.loadModel(sess)

        for key, img in testImg.items():
            # img preprocess
            resized = cv2.resize(img.astype(np.float), (227, 227)) - imgMean
            maxx = np.argmax(
                sess.run(softmax,
                         feed_dict={x: resized.reshape((1, 227, 227, 3))}))
            res = caffe_classes.class_names[maxx]
BATCH_SIZE = 108
CAPACITY = 2000
dropout = 1.0
train_txt = 'train.txt'
val_txt = 'val.txt'
model_dir = './model_sample/'

if not os.path.exists('./features'):
    os.mkdir('./features')

with tf.Graph().as_default():

    batch, label_batch, n = make_data.get_batch(val_txt, IMG_W, IMG_H,
                                                BATCH_SIZE, CAPACITY)
    x = tf.placeholder(tf.float32, shape=[BATCH_SIZE, IMG_W, IMG_H, 3])
    train_model = alexnet.alexNet(x, dropout, N_CLASSES)
    feature_fc = train_model.fc2
    saver = tf.train.Saver(tf.global_variables())

    with tf.Session() as sess:
        ckpt = tf.train.get_checkpoint_state(model_dir)
        if ckpt and ckpt.model_checkpoint_path:
            global_step = ckpt.model_checkpoint_path.split('/')[-1].split(
                '-')[-1]
            saver.restore(sess, ckpt.model_checkpoint_path)
            print('Loading success, global_step is %s' % global_step)

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)

        try:
IMG_W = 100
IMG_H = 100

train_filename = '/home/wu/TF_Project/action/sample_TFrecord/train1.tfrecords'
#dir = '/home/wu/TF_Project/action/feature_tensorboard/'
dir = '/home/wu/TF_Project/action/features/'
train_img, train_label = tfrecord.read_and_decode(train_filename)
train_batch, train_label_batch = tf.train.shuffle_batch(
    [train_img, train_label],
    batch_size=100,
    num_threads=64,
    capacity=2000,
    min_after_dequeue=1000)
x = tf.placeholder(tf.float32, shape=[BATCH_SIZE, IMG_W, IMG_H, 3])

train_model = alexnet.alexNet(x)
conv1_feature = train_model.conv1
"""
state = tf.Variable(0, name='counter')
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
"""
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord, sess=sess)

    train_model.load_initial_weights(sess)

    #summary_op = tf.summary.merge_all()
Пример #9
0
        return image


    testImg = {args.path: url2img(args.path)}

# noinspection PyUnboundLocalVariable
if testImg.values():
    # some params
    dropoutPro = 1
    classNum = 1000
    skip = []

    imgMean = np.array([104, 117, 124], np.float)
    x = tf.placeholder("float", [1, 227, 227, 3])

    model = alexnet.alexNet(x, dropoutPro, classNum, skip)
    score = model.fc3
    softmax = tf.nn.softmax(score)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        model.loadModel(sess)

        for key, img in testImg.items():
            # img preprocess
            resized = cv2.resize(img.astype(np.float), (227, 227)) - imgMean
            maxx = np.argmax(sess.run(softmax, feed_dict={x: resized.reshape((1, 227, 227, 3))}))
            res = caffe_classes.class_names[maxx]

            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(img, res, (int(img.shape[0] / 3), int(img.shape[1] / 3)), font, 1, (0, 255, 0), 2)