Example #1
0
def test_combo_feature(train_dir, test_dir, force_run = False):
    # Uncomment the following line if you extracted training
    # data from .png images (scaled 0 to 1 by mpimg) and the
    # image you are searching is a .jpg (scaled 0 to 255)
    #image = image.astype(np.float32)/255
    scspace = 'BGR'
    dcspace = 'YCrCb'  # Can be RGB, HSV, LUV, HLS, YUV, YCrCb
    orient = 9  # HOG orientations
    pix_per_cell = 8  # HOG pixels per cell
    cell_per_block = 2  # HOG cells per block
    hog_channel = '012'  # Can be 0, 1, 2, or "012"
    spatial_size = (32, 32)  # Spatial binning dimensions
    hist_bins = 32    # Number of histogram bins
    spatial_feat = True  # Spatial features on or off
    hist_feat = True  # Histogram features on or off
    hog_feat = True  # HOG features on or off
    y_start_stop = [None, None]  # Min and max in y to search in slide_window()

    if have_classifier() and force_run == False:
        svc, scaler, dcspace, spatial_size, hist_bins, orient, \
        pix_per_cell, cell_per_block, hog_channel, spatial_feat, hist_feat, hog_feat = load_classifier()
    else:
        svc, scaler = combo_feature_train(train_dir, scspace=scspace, dcspace=dcspace,
                                          spatial_size=spatial_size, hist_bins=hist_bins,
                                          orient=orient, pix_per_cell=pix_per_cell,
                                          cell_per_block=cell_per_block,
                                          hog_channel=hog_channel, spatial_feat=spatial_feat,
                                          hist_feat=hist_feat, hog_feat=hog_feat)

    fnames = load_images(test_dir)
    for fname in fnames:
        image = cv2.imread(fname)
        draw_image = np.copy(image)
        draw_image = color_convert_nocheck(image, 'BGR', 'RGB')

        image = cv2.resize(image, (64, 64))

        features = combo_feature(image, scspace=scspace, dcspace=dcspace,
                                 spatial_size=spatial_size, hist_bins=hist_bins,
                                 orient=orient, pix_per_cell=pix_per_cell,
                                 cell_per_block=cell_per_block,
                                 hog_channel=hog_channel, spatial_feat=spatial_feat,
                                 hist_feat=hist_feat, hog_feat=hog_feat)
        # 5) Scale extracted features to be fed to classifier
        test_features = scaler.transform(np.array(features).reshape(1, -1))
        # 6) Predict using your classifier
        prediction = svc.predict(test_features)

        basename = os.path.basename(fname)
        name, ext = os.path.splitext(basename)
        savename = os.path.join('output_images', name + "_classify" + ext)
        fig = plt.figure()
        plt.imshow(draw_image)
        if prediction == 1:
            plt.title('Original Image is car')
        else:
            plt.title('Original image is not car')
        plt.xlabel('fname')
        fig.savefig(savename)
Example #2
0
def main():
    model_folder = "./model/" + train_id

    if not os.path.exists(model_folder):
        os.makedirs(model_folder)
    model_dir = model_folder + "/final.pth"

    train_data = load_data.load_images(train_dir, train_batch_size)
    val_data = load_data.load_images(val_dir, val_batch_size)

    net = network.UNet(1, 1).to(device)
    net.apply(network.init)

    net = train.train_model(net, train_data, val_data, num_epochs, device,
                            train_id)

    torch.save(net.state_dict(), model_dir)

    test.evaluate(model_dir)
def gen_patches(model, input_dir, output_dir, max_out=None):
    img_names = os.listdir(input_dir)

    if max_out is not None:
        img_names = img_names[:max_out]

    lossy_patches = load_images(input_dir, img_names)

    predictions = model.predict(lossy_patches)
    write_images(output_dir, img_names, predictions)

    print 'generated %i images with the CNN' % predictions.shape[0]
Example #4
0
def gen_patches(model, input_dir, output_dir, max_out=None):
    img_names = os.listdir(input_dir)

    if max_out is not None:
        img_names = img_names[:max_out]

    lossy_patches = load_images(input_dir, img_names)

    predictions = model.predict(lossy_patches)
    write_images(output_dir, img_names, predictions)

    print 'generated %i images with the CNN' % predictions.shape[0]
Example #5
0
def train_subclass(train_lists, test_lists, image_size, epochs):
    """
    对比赛数据集顶层大类中的子类进行训练
    :param train_lists:子类训练集文件路径
    :param test_lists:子类测试集文件路径
    :param image_size:图片张量
    :param epochs:循环的次数
    :return:null
    """
    for (train_list, test_list) in zip(train_lists, test_lists):
        # 分别读取路径列表中的图片
        print("[INFO] loading subclass images...")
        x_train, y_train = load_images(train_list, image_size)
        x_test, y_test = load_images(test_list, image_size)
        # 加载并设置模型
        print('[INFO] loading model...')
        model = reset_model('models/evaluation_top_model.h5',
                            len(os.listdir(train_list)))
        # 训练模型
        # 模型名称以父类型名称命名
        print("[INFO] compiling " + os.path.split(train_list)[1] + " model...")
        train(model, x_train, y_train, x_test, y_test,
              len(y_train) // 10, epochs,
              'models/' + os.path.split(train_list)[1] + '.h5')
Example #6
0
def load_photos():
    df = load_data.read_data()

    # Get names
    pizza_names, pizza_eng_names = load_data.get_pizza_names(df)
    print(pizza_eng_names)

    # prepare image paths
    image_paths = []
    for name in pizza_eng_names:
        path = os.path.join(name, name + '3.jpg')
        image_paths.append(path)
    print(image_paths)

    images = load_data.load_images(image_paths)

    # cut pizza from photo
    pizza_imgs = load_data.cut_pizza_from_images(images)

    return pizza_eng_names, pizza_imgs
def test_sliding_window(path):
    fnames = load_images(path)

    y_start_stop = [400, 656]
    for fname in fnames:
        image = cv2.imread(fname)
        image = color_convert_nocheck(image, 'BGR', 'RGB')
        windows = slide_window(image,
                               x_start_stop=[None, None],
                               y_start_stop=y_start_stop,
                               xy_window=(64, 64),
                               xy_overlap=(0.75, 0.75))

        window_img = draw_boxes(image, windows, color=(0, 0, 255), thick=2)
        basename = os.path.basename(fname)
        name, ext = os.path.splitext(basename)
        savename = os.path.join('output_images', name + "_window" + ext)
        fig = plt.figure(figsize=(16, 8))
        plt.imshow(window_img)
        plt.title('Sliding Window')
        plt.xlabel(fname)
        fig.savefig(savename)
Example #8
0
def validate_perspective_transform(inputdir, outputdir):
    fnames = load_images(inputdir)

    for fname in fnames:
        image = cv2.imread(fname)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        image = undistort(image)

        basename = os.path.basename(fname)
        savename = os.path.join(outputdir, basename)

        src = np.copy(image)
        src = draw_src_rectangle(src)
        save_image(src, savename, 'persp_src')

        dst = persp_trans_forward(image)
        dst = draw_dst_rectangle(dst)
        save_image(dst, savename, 'persp_dst')

        basename = os.path.basename(fname)
        head, ext = os.path.splitext(basename)
        savename = os.path.join('output_images', head + '_perspective' + ext)
        w = image.shape[1]
        h = image.shape[0]
        dpi = 96
        fig = plt.figure(figsize=(w / dpi, h / dpi))
        plt.suptitle(fname)
        plt.subplot(121)
        plt.imshow(src)
        plt.title('Undistort Image')
        plt.subplot(122)
        plt.imshow(dst)
        plt.title('Perspective Transform')
        #plt.xlabel(fname)
        fig.tight_layout()
        fig.savefig(savename, dpi=dpi)
        plt.close()
def test_undistort(path):
    fnames = load_images(path)
    for fname in fnames:
        do_undistort(fname)
Example #10
0
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

sess.run(tf.initialize_all_variables())

datasets = ['./data/data_batch_1', './data/data_batch_2', './data/data_batch_3', './data/data_batch_4','./data/data_batch_5']
epoch = input('\nPlease input epoch:')
batch_size = input('Please input batch size:')
temp = 50000/batch_size

t1 = time.time()
start_index = 0
images = np.zeros([50000, 32, 32, 3])
labels = np.zeros([50000, 10])
for j in xrange(5):
	images[j*10000:(j+1)*10000] = load_data.load_images(datasets[j])
	labels[j*10000:(j+1)*10000] = load_data.load_labels(datasets[j])


for i in xrange(epoch * temp):
	batch_x, batch_y, start_index = load_data.next_batch(images, labels, batch_size, start_index)
	_, loss_val = sess.run([train_step, cross_entropy], feed_dict={x:batch_x, y_:batch_y, keep_prob: 0.8})
	if i%temp == 0:
		print 'epoch %d , loss = %s' % (i/temp, loss_val)

del images, labels

print '\nEnd training.\n'
t2 = time.time()

test_x, test_y = load_data.load_data('./data/test_batch')
                  'W15': W15,  # 'b15' : b15,
                  'W16': W16}  # 'b16' : b16}

    return parameters


# nh = 64  # height of input image
# nw = 64  # width of input image
# n_ch = 3  # initial  number of channels
d = 64  # size of the encoding
temp_path = "C:\My Folder\Programming\Deep Learning\Colorization\\temp\\"
# X = tf.placeholder("float32", shape = [None, 64, 64, 2], name = 'Input image data')


### Train VAE
X, G = load_images("./lfw-deepfunneled")
print("data loaded")
parameters = initialize_parameters(3, d)
print("parameters initialized")
parameters = train_vae(X, parameters, d, 100, 64, temp_path, 0.009, 1.0)
### save encodings
z = get_encodings(X, d, 1.0, parameters)
np.save(temp_path + "encodings", z)

### train MDN
z = np.load(temp_path + "encodings")
train_mdn(G, z, 100, d, 1.0, parameters, 0.009, 16, temp_path)

# G = tf.placeholder('float32', shape = [None, 28, 28, 512], name= 'Grey level features')
# X = tf.random_normal([320, 64, 64,2], mean = 0.04, stddev = 0.97, dtype = tf.float32, seed =0, name = 'X')
Example #12
0
# 主函数
if __name__ == '__main__':

    print('[INFO] start...')
    args = args_parse()

    if args.function == 1:
        # 利用参考数据集训练模型
        # 扩展参考数据集路径
        background_train_path = args.train_path
        # 参考测试数据集路径
        background_test_path = args.test_path
        # 读取参考训练数据和测试数据
        print("[INFO] loading background images...")
        x_train_background, y_train_background = load_images(
            background_train_path, IMAGE_SIZE)
        x_test_background, y_test_background = load_images(
            background_train_path, IMAGE_SIZE)
        # 初始化模型
        print("[INFO] initialize background model...")
        background_model = creat_model(FILTERS, KERNEL_SIZE, INPUT_SHAPE,
                                       POOL_SIZE,
                                       len(os.listdir(background_train_path)))
        # 训练模型
        print("[INFO] compiling background model...")
        train(background_model, x_train_background, y_train_background,
              x_test_background, y_test_background,
              len(y_train_background) // 10, EPOCHS,
              'models/backgroud_model.h5')
    elif args.function == 2:
        # 使用迁移学习训练比赛集
Example #13
0
import numpy as np
from load_data import load_images, load_dataset
from process_data import detect_face
from embedding import get_embedded_data
from train import get_svm_model, normalize

from keras.models import load_model
from sklearn.preprocessing import LabelEncoder

import matplotlib.pyplot as plt
import joblib

if __name__ == '__main__':
    input_dir = 'play'

    images = load_images(input_dir)
    cropped_images = list()

    for i in range(len(images)):
        cropped_images.append(detect_face(images[i]))

    face_model = load_model(os.path.join('model', 'facenet_keras.h5'))
    cropped_images = get_embedded_data(face_model, cropped_images)

    cropped_images = normalize(cropped_images)

    model = joblib.load(os.path.join('model', 'svm_model.sav'))

    pred_test = model.predict(cropped_images)
    pred_proba = model.predict_proba(cropped_images)
from cnn import build_cnn_model

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

#train_images, train_labels, train_length = load_images_negative(folder = 'train', augmentation = False, quick_load = False)
#test_images, test_labels, test_length = load_images(folder = 'test', augmentation = False, quick_load = False)

train_images, train_labels, train_length = load_images_negative(folder = 'train', augmentation = False, quick_load = True)
extra_images, extra_labels, extra_length = load_images_negative(folder = 'extra', augmentation = False, quick_load = True)

train_images = np.concatenate((train_images, extra_images), axis=0)
train_labels = np.concatenate((train_labels, extra_labels), axis=0)
train_length = np.concatenate((train_length, extra_length), axis=0)

test_images, test_labels, test_length = load_images(folder = 'test', augmentation = False, quick_load = True)
test_images, test_labels, test_length = load_images(folder = 'test', augmentation = False, quick_load = True)

np.save('train_images.npy', train_images)
np.save('train_labels.npy', train_labels) 
np.save('train_length.npy', train_length) 

np.save('test_images.npy',test_images) 
np.save('test_labels.npy',test_labels) 
np.save('test_length.npy',test_length) 

train_images = np.load('train_images.npy')
train_labels = np.load('train_labels.npy') 
train_length = np.load('train_length.npy') 

test_images = np.load('test_images.npy') 
Example #15
0
if __name__ == "__main__":

    # This is where we write the images, if an output_dir is given
    # in command line:
    out_dir = None
    names = ['Arpit', 'Jane', 'Jack']
    # You'll need at least a path to your image data, please see
    # the tutorial coming with this source code on how to prepare
    # your image data:
    if len(sys.argv) < 2:
        print(
            "USAGE: facerec_demo.py </path/to/images> [</path/to/store/images/at>]"
        )
        sys.exit()
    # Now read in the image data. This must be a valid path!
    [X, y] = load_images(sys.argv[1])
    # Convert labels to 32bit integers. This is a workaround for 64bit machines,
    # because the labels will truncated else. This will be fixed in code as
    # soon as possible, so Python users don't need to know about this.
    # Thanks to Leo Dirac for reporting:
    y = np.array(y, dtype=np.int32)
    # If a out_dir is given, set it:
    if len(sys.argv) == 3:
        out_dir = sys.argv[2]
    # Create the Eigenfaces model. We are going to use the default
    # parameters for this simple example, please read the documentation
    # for thresholding:
    #model = cv2.face.createLBPHFaceRecognizer()
    model = cv2.face.EigenFaceRecognizer_create()
    # Read
    # Learn the model. Remember our function returns Python lists,
Example #16
0
def test_hog_scale(path):
    svc, scaler, dcspace, spatial_size, hist_bins, orient, pix_per_cell, cell_per_block, hog_channel, spatial_feat, hist_feat, hog_feat = load_classifier(
    )

    #input_name = 'test1.jpg'
    #img = mpimg.imread(input_name)

    ystart = 400
    ystop = 656
    scale = 1.5
    scspace = 'BGR'

    fnames = load_images(path)
    for fname in fnames:
        img = load_image(fname, scspace)
        print("processing", fname)
        heat = np.zeros_like(img[:, :, 0]).astype(np.float)
        for scale in (1.0, 1.5, 2.0):
            out_img, boxes = find_cars(img,
                                       scspace,
                                       dcspace,
                                       ystart,
                                       ystop,
                                       scale,
                                       svc,
                                       scaler,
                                       orient,
                                       pix_per_cell,
                                       cell_per_block,
                                       spatial_size,
                                       hist_bins,
                                       draw=True)

            add_heat(heat, boxes)
            # plt.imshow(out_img)

            basename = os.path.basename(fname)
            name, ext = os.path.splitext(basename)
            savename = os.path.join('output_images',
                                    name + "_subsample_" + str(scale) + ext)
            fig = plt.figure()
            plt.imshow(out_img)
            fig.savefig(savename)
            plt.close()

        heat = apply_threshold(heat, 1)
        heatmap = np.clip(heat, 0, 255)
        labels = label(heatmap)

        basename = os.path.basename(fname)
        name, ext = os.path.splitext(basename)
        savename = os.path.join('output_images', name + "_heatmap" + ext)
        fig = plt.figure()
        plt.imshow(heatmap, cmap='gray')
        fig.savefig(savename)
        plt.close()
        draw_labels = np.zeros_like(img[:, :, 0]).astype(np.uint8)
        draw_labels = draw_labeled_bboxes_solid(draw_labels, labels)
        savename = os.path.join('output_images', name + "_labels" + ext)
        fig = plt.figure()
        plt.imshow(draw_labels, cmap='gray')
        fig.savefig(savename)
        plt.close()
Example #17
0
    model.add(Flatten())
    model.add(Dense(4048, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4048, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(6, activation='softmax'))

    return model


seed = 13
np.random.seed(seed)

# Load training dataset
print("Attempt to load training dataset")
X_train, Y_train = load_images('datasets/training_images/')

print("Training dataset succefully loaded")

# Load validation dataset
print("Attempt to load validation dataset")
X_valid, Y_valid = load_images('datasets/validation_images/')

print("Validation dataset succefully loaded")

print("Creating model")
model = VGG_S()

print("Compiling model")
model.compile(loss='binary_crossentropy',
              optimizer='adam',
Example #18
0
if __name__ == "__main__":

    sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

    #rot_images, rot_labels, rot_length = load_images_rot(folder='train',img_shape = 224, resize_shape =224, crops =3, augmentation=True)
    train_images, train_labels, train_length = load_images_negative(
        folder='train',
        img_shape=224,
        resize_shape=224,
        augmentation=False,
        quick_load=False)
    #extra_images, extra_labels, extra_length = load_images_negative(folder = 'extra', img_shape = 224, resize_shape =224,  augmentation = False, quick_load = False)
    test_images, test_labels, test_length = load_images(folder='test',
                                                        img_shape=224,
                                                        resize_shape=224,
                                                        augmentation=False,
                                                        quick_load=False)

    print(train_images.shape)
    print(train_labels.shape)
    print(train_length.shape)

    print(test_images.shape)
    print(test_labels.shape)
    print(test_length.shape)

    # initialize the optimizer and  the model
    EPOCHS = 20
    INIT_LR = 1e-4
    BS = 32
def test_hls_process(path):
    fnames = load_images(path)

    for fname in fnames:
        hls_process(fname)
Example #20
0
def apply_window_search(train_dir, test_dir):
    # Uncomment the following line if you extracted training
    # data from .png images (scaled 0 to 1 by mpimg) and the
    # image you are searching is a .jpg (scaled 0 to 255)
    #image = image.astype(np.float32)/255
    dcspace = 'YCrCb'  # Can be RGB, HSV, LUV, HLS, YUV, YCrCb
    orient = 9  # HOG orientations
    pix_per_cell = 8  # HOG pixels per cell
    cell_per_block = 2  # HOG cells per block
    hog_channel = '012'  # Can be 0, 1, 2, or "012"
    spatial_size = (32, 32)  # Spatial binning dimensions
    hist_bins = 32    # Number of histogram bins
    spatial_feat = True  # Spatial features on or off
    hist_feat = True  # Histogram features on or off
    hog_feat = True  # HOG features on or off
    y_start_stop = [None, None]  # Min and max in y to search in slide_window()
    if have_classifier():
        svc, scaler, dcspace, spatial_size, hist_bins, orient, \
        pix_per_cell, cell_per_block, hog_channel, spatial_feat, hist_feat, hog_feat = load_classifier()
    else:
        svc, scaler = combo_feature_train(train_dir, scspace='BGR', dcspace=dcspace,
                                          spatial_size=spatial_size, hist_bins=hist_bins,
                                          orient=orient, pix_per_cell=pix_per_cell,
                                          cell_per_block=cell_per_block,
                                          hog_channel=hog_channel, spatial_feat=spatial_feat,
                                          hist_feat=hist_feat, hog_feat=hog_feat)

    fnames = load_images(test_dir)

    for fname in fnames:
        image = cv2.imread(fname)
        draw_image = np.copy(image)
        draw_image = color_convert_nocheck(image, 'BGR', 'RGB')

        min_window = spatial_size[0]
        max_window = 128

        top_y = int(image.shape[0] / 2)
        y_start_stop = [top_y, image.shape[0]]
        valid_y = image.shape[0] - top_y
        for window_size in range(min_window, max_window, spatial_size[0]):
            #window_size = int(min_window * scale_factor)
            #print("window size", window_size, "larger than", image.shape[0], "x", image.shape[1])

            if window_size > valid_y or window_size > image.shape[1]:
                print("window size", window_size, "larger than",
                      valid_y, "x", image.shape[1])
                continue

            windows = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,
                                   xy_window=(window_size, window_size), xy_overlap=(0.75, 0.75))

            hot_windows = search_windows(image, windows, svc, scaler, scspace='BGR', dcspace=dcspace,
                                         spatial_size=spatial_size, hist_bins=hist_bins,
                                         orient=orient, pix_per_cell=pix_per_cell,
                                         cell_per_block=cell_per_block,
                                         hog_channel=hog_channel, spatial_feat=spatial_feat,
                                         hist_feat=hist_feat, hog_feat=hog_feat)

            window_img = draw_boxes(draw_image, hot_windows,
                                    color=(0, 0, 255), thick=5)

            plt.imshow(window_img)
            basename = os.path.basename(fname)
            name, ext = os.path.splitext(basename)
            savename = os.path.join(
                'output_images', name + "_" + str(window_size) + "_" + ext)
            fig = plt.figure()
            plt.imshow(window_img)
            plt.title('Searching window size' + str(window_size))
            plt.xlabel(fname)
            fig.savefig(savename)
            plt.close()
                     embeddings_layer_names=None,
                     embeddings_metadata=None)
    # 提前结束训练
    # early_stopping = EarlyStopping(monitor='val_loss', patience=3)
    callbacks = [tb]
    
    # 配置训练模型
    model.compile(optimizer=Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08), metrics=['accuracy'], loss='categorical_crossentropy')
    # 图像扩充,左右随机裁剪20%像素,以30度的角度进行旋转
    data_gen = ImageDataGenerator(rotation_range = 30, width_shift_range=0.2, height_shift_range=0.2)
    # 逐批生成数据训练模型
    model.fit_generator(data_gen.flow(x_train, y_train, batch_size=batch_size),
                       steps_per_epoch=len(x_train) / batch_size, epochs=epochs,
                       verbose=1, validation_data=(x_test, y_test), callbacks=callbacks)
    # 训练结束保存模型
    print("[INFO] save model...")
    model.save(model_name)


if __name__=='__main__':
    print('[INFO] start...')
    train_images_path = "data/CK+48_train" # 训练集
    test_images_path = "data/CK+48_test"# 测试集

    # 加载图片
    x_train_background, y_train_background = load_images(train_images_path, IMAGE_SIZE)
    x_test_background, y_test_background = load_images(test_images_path, IMAGE_SIZE)
    #初始化模型
    model = initialize_model(FILTERS, KERNEL_SIZE, INPUT_SHAPE, POOL_SIZE,len(os.listdir(train_images_path)))
    # 训练模型
    train(model, x_train_background, y_train_background, x_test_background, y_test_background, 8, EPOCHS, 'models/base_model.h5')
Example #22
0
def main(_):
    batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
    num_classes = 1001

    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)

    # Prepare graph
    x_input = tf.placeholder(tf.float32, shape=batch_shape)
    y_label = tf.placeholder(tf.int32, shape=(FLAGS.batch_size, ))
    y_hot = tf.one_hot(y_label, num_classes)

    model = InceptionModel(num_classes)
    preds = model(x_input)
    logits = model.get_logits(x_input)
    acc = _top_1_accuracy(logits, y_label)
    tf_model_load(sess, FLAGS.checkpoint_path)

    attack = KKTFun5(model, sess=sess)
    eps = FLAGS.eps
    alp = FLAGS.alp
    params = {
        'eps': 0.3,
        'alp': 1.0,
        'ord': 2,
        'nb_iter': eps,
        'clip_min': 0.,
        'clip_max': 1.
    }
    adv_x, log_step, log_suc = attack.generate(x_input, y_label, **params)
    adv_image = np.zeros((1000, 299, 299, 3))
    l2_norm = np.zeros((1000))
    acc_ori = np.zeros((1000))
    acc_val = np.zeros((1000))
    pred_score = np.zeros((1000, 1001))
    pred_score_adv = np.zeros((1000, 1001))
    name = []
    b_i = 0

    begin = time.time()
    for images, _, labels, filenames in load_images(FLAGS.input_dir,
                                                    FLAGS.input_dir,
                                                    FLAGS.metadata_file_path,
                                                    batch_shape):
        bb_i = b_i + FLAGS.batch_size
        y_labels = np.zeros((FLAGS.batch_size, num_classes))
        for i_y in range(FLAGS.batch_size):
            y_labels[i_y][labels[i_y]] = 1
        x_adv = sess.run(adv_x, feed_dict={x_input: images, y_label: labels})
        #acc_val[b_i:bb_i] = sess.run(log_suc,feed_dict={x_input:images,y_label:labels})
        #l2_norm[b_i:bb_i] = sess.run(log_step,feed_dict={x_input:images,y_label:labels})
        #pdb.set_trace()
        #acc_ori[b_i] = sess.run(acc,feed_dict={x_input:images,y_label:labels})
        #l2_norm[b_i] = np.mean(np.sum((images- x_adv)**2,axis=(1,2,3))**.5)
        adv_image[b_i:bb_i] = x_adv
        acc_ori[b_i:bb_i] = sess.run(acc,
                                     feed_dict={
                                         x_input: images,
                                         y_label: labels
                                     })
        acc_val[b_i:bb_i] = sess.run(acc,
                                     feed_dict={
                                         x_input: x_adv,
                                         y_label: labels
                                     })
        pred_score[b_i:bb_i] = sess.run(preds,
                                        feed_dict={
                                            x_input: images,
                                            y_label: labels
                                        })
        pred_score_adv[b_i:bb_i] = sess.run(preds,
                                            feed_dict={
                                                x_input: x_adv,
                                                y_label: labels
                                            })
        l2_norm[b_i:bb_i] = np.sum((x_adv - images)**2, axis=(1, 2, 3))**.5
        name.append(filenames)
        b_i = bb_i
Example #23
0
    # 从图片列表中遍历每一张需要识别的图片
    image_count = len(image_lists)
    true_count = 0
    for image in image_lists:
        result = model.predict(image[0])[0]  # 将图片送入模型中预测
        proba = np.max(result)  # 取出相似度最高的一项
        label = kind_lists[int(np.where(result == proba)[0])]  # 获得识别出类型的标签
        # 打印分类log
        log = ("result:" + label + " -> " + str(proba * 100) + " -> source:" +
               image[1] + " -> name:" + image[2] + " -> path:" + image[3] +
               "\n")
        print(log)
        # 判断识别结果是否正确
        if label == image[1]:
            true_count += 1
        else:
            # 输出分类错误日志到文件
            with open("logs/log.txt", "a") as f:
                f.write(log)

    print("分类图片总数:{}, 分类正确:{}, 分类正确率:{}%".format(
        image_count, true_count, (true_count / image_count) * 100))


if __name__ == '__main__':
    # 测试模型并输出分类日志
    test_data_path = "data/CK+48_test"  # 测试集
    model_path = "models/ck+48_model.h5"  # 测试模型
    image_lists = load_images(test_data_path, IMAGE_SIZE)  # 加载测试图片
    model = load_model(model_path)  # 加载测试模型
    classify_image(model, image_lists, KIND_LISTS)