Пример #1
0
def evulate_each_class(breed):
    acc = 0
    data_dir = os.path.join('./input/test1/', breed)

    al_list = os.listdir(data_dir)
    print(al_list)
    for filepath in al_list:
        # Read one image
        img = read_img(data_dir, filepath, (INPUT_SIZE, INPUT_SIZE))
        # x = keras.applications.xception.preprocess_input(np.expand_dims(img.copy(), axis=0))
        x = keras.applications.vgg16.preprocess_input(
            np.expand_dims(img.copy(), axis=0))

        preds = loaded_model.predict(x)
        max_index = np.argmax(preds)

        class_name = CATEGORIES[max_index]
        prob = preds[0][max_index]
        if class_name == breed:
            acc += 1

        print('ground truth : {}, prediction : {}, probability : {}'.format(
            breed, class_name, prob))
    avg_acc = acc / len(al_list) * 1.0
    print('accuracy on {} images of {} is {}'.format(len(al_list), breed,
                                                     avg_acc))
    return avg_acc
Пример #2
0
def predictwhole(image, X, mode, pred):
    proj, geotrans, input_img = read_img(image)
    predfunc = (lambda img: sess.run(pred, feed_dict={X: img, mode: False}))
    onebatch = []
    onebatch.append(input_img)
    one_batch = np.array(onebatch)
    pred_result = predfunc(onebatch)
    print(pred_result)
Пример #3
0
def predict(data_dir, output_dir, X, mode, pred):
    if not os.path.exists(output_dir):
        os.mkdir(output_dir)
    for i in range(0, 15000, 5000):
        for j in range(0, 15000, 5000):
            one_data = '%s/tile_%d_%d.tif' % (data_dir, i, j)
            one_data_output = '%s/pred_tile_%d_%d.tif' % (output_dir, i, j)
            print ("predict tile_%d_%d.tif" % (i, j))
            proj, geotrans, input_img = read_img(one_data)
            label_pred_tiny = predict_img_with_smooth_windowing(
                input_img,
                window_size=768,
                subdivisions=2,
                batch_size=8,
                pred_func=(
                    lambda img: sess.run(pred, feed_dict={X: img, mode: False})
                )
            )
            label_pred_tiny = label_pred_tiny[:, :, 0]
            # label_pred_tiny[np.where(label_pred_tiny >= 0.3)] = 255
            label_pred_tiny[label_pred_tiny<0.1] = 0
            label_pred_tiny = label_pred_tiny.astype(np.float32)
            write_img(one_data_output, proj, geotrans, label_pred_tiny)
Пример #4
0
def post_process(prediction, class_idx, z_mask, out_path):
    # print('post processing ...')
    # 4. make predicted map and label map have the same index
    # print('prediction', np.unique(np.ravel(prediction)))

    # ind_mask = []
    class_idx.reverse()
    for i, num in enumerate(class_idx):
        ind_mask = (prediction == len(class_idx)-i-1)
        # print(i, np.sum(ind_mask[-1]))
        prediction[ind_mask] = num

    # print('prediction', np.unique(np.ravel(prediction)))
    prediction[z_mask.astype(np.bool)] = 0
    # print('prediction', np.unique(np.ravel(prediction)))

    # 5. store prediction result
    im_projection, im_geo_transformation = read_img(flags.image, only_coordinate=True)
    write_img(filename=out_path, im_proj=im_projection, im_geotrans=im_geo_transformation, im_data=prediction)
    # print('post process done ! now store the image')
    # io.imsave(out_path, prediction)
    class_idx.reverse()
    return prediction
### Ploting the photos

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

j = int(np.sqrt(nb_test_images))
i = int(np.ceil(1. * nb_test_images / j))
print("i={}, j={}".format(i, j))
fig = plt.figure(1, figsize=(32, 32))
grid = ImageGrid(fig, 111, nrows_ncols=(i, j), axes_pad=0.05)

for i in range(nb_test_images):
    ax = grid[i]
    # Read one image
    img = read_img(data_dir, al_list[i], (INPUT_SIZE, INPUT_SIZE))
    ax.imshow(img / 255.)
    # x = keras.applications.xception.preprocess_input(np.expand_dims(img.copy(), axis=0))
    x = keras.applications.vgg16.preprocess_input(np.expand_dims(img.copy(), axis=0))

    preds = loaded_model.predict(x)
    max_index = np.argmax(preds)

    class_name = CATEGORIES[max_index]
    prob = preds[0][max_index]

    print('groud truth : {}, prediction : {}, probability : {}'.format(breed, class_name, prob))

    ax.text(10, 180, 'VGG16: %s (%.2f)' % (class_name , prob), color='w', backgroundcolor='k', alpha=0.8)
    ax.text(10, 200, 'LABEL: %s' % breed, color='k', backgroundcolor='w', alpha=0.8)
    ax.axis('off')
Пример #6
0
    # make predicted map and label map have the same index
    ind_mask = []
    for i, num in enumerate(class_idx):
        ind_mask.append(prediction == i)
        # print(i, np.sum(ind_mask[-1]))
    for i, num in enumerate(class_idx):
        prediction[ind_mask[i]] = num
    prediction[zero_mask] = 0

    print(np.unique(np.ravel(prediction)))

    # generate pseudo color
    colors = np.random.randint(0,
                               255,
                               size=(len(class_idx) * 3, ),
                               dtype=np.uint8).reshape(-1, 3)
    pseudo = np.zeros((prediction.shape[0], prediction.shape[1], 3),
                      dtype=np.uint8)
    print(colors)
    for i, idx in enumerate(class_idx):
        pseudo[prediction == idx, :] = colors[i, :]

    im_proj, im_geotrans = read_img(flags.image, only_coordinate=True)
    write_img(filename=flags.output,
              im_proj=im_proj,
              im_geotrans=im_geotrans,
              im_data=prediction)
    # io.imsave(flags.output, prediction)
    io.imsave('./pseudo.png', pseudo)
Пример #7
0
def predict(data_dir, output_dir, X, mode, pred):

    print("reading image...")
    proj, geotrans, input_img = read_img(data_dir)
    # input_img[:, :, [2, 0]] = input_img[:, :, [0, 2]]
    input_img = input_img[:, :, :3]
    print(input_img.shape)
    input_img = np.asarray(input_img, dtype='uint8')

    step = 32
    height, width, _ = input_img.shape
    print(height // step)
    print(width // step)
    for i in range(height // step):
        if i == height // step and height // step != 0:
            continue
        for j in range(width // step + 1):
            if j == width // step and width // step != 0:
                continue
            last_height_value = (
                i + 1) * step if i + 1 != height // step else height
            last_width_value = (j +
                                1) * step if j + 1 != width // step else width
            cv2.imwrite(
                '%s/tmp_%d_%d.jpg' % (tmp_dir, i, j),
                input_img[i * step:last_height_value,
                          j * step:last_width_value, :])
            print('%s/tmp_%d_%d.jpg write done' % (tmp_dir, i, j))

    del input_img
    gc.collect()
    print("done1")
    label_pred = np.zeros((height, width), dtype=np.uint8)
    for i in range(height // step):
        if i == height // step and height // step != 0:
            continue
        for j in range(width // step + 1):
            if j == width // step and width // step != 0:
                continue
            last_height_value = (
                i + 1) * step if i + 1 != height // step else height
            last_width_value = (j +
                                1) * step if j + 1 != width // step else width
            print(last_height_value, last_width_value)
            print('%s/tmp_%d_%d.jpg' % (tmp_dir, i, j))
            img_tiny = cv2.imread('%s/tmp_%d_%d.jpg' % (tmp_dir, i, j))
            print(img_tiny)
            label_pred_tiny = predict_img_with_smooth_windowing(
                img_tiny,
                window_size=32,
                subdivisions=2,
                batch_size=64,
                pred_func=(
                    lambda img: sess.run(pred, feed_dict={
                        X: img,
                        mode: False
                    })))
            label_pred_tiny = label_pred_tiny[:, :, 0]
            label_pred_tiny[np.where(label_pred_tiny >= 0.5)] = 1
            label_pred_tiny[np.where(label_pred_tiny < 0.5)] = 0
            label_pred_tiny = label_pred_tiny.astype(np.uint8)
            label_pred[i * step:last_height_value,
                       j * step:last_width_value] = label_pred_tiny

    gc.collect()
    print("done2")
    # cv2.imwrite(output_dir, label_pred)
    write_img(output_dir, proj, geotrans, label_pred)

    print("done3")
Пример #8
0
import tifffile as tif
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import cv2
from tools import read_img, write_img

if __name__ == "__main__":
    pred_label_file = "../data/pine/pred_classes.tif"
    test_label_file = "../data/pine/test_classes.tif"
    pred_label_file_png = "../data/pine/pred_classes.png"
    proj, geotrans, input_img = read_img(test_label_file)
    pred = cv2.imread(pred_label_file)
    write_img(pred_label_file, proj, geotrans, pred)