示例#1
0
# check if weight path was passed via command line
if options.input_weight_path:
	C.base_net_weights = options.input_weight_path
else:
	# set the path to weights based on backend and model
	C.base_net_weights = nn.get_weight_path()


# place weight files on your directory
ase_net_weights = nn.get_weight_path()


#### load images here ####
# get voc images
all_imgs, classes_count, class_mapping = get_data(options.train_path)

print(classes_count)

# add background class as 21st class
if 'bg' not in classes_count:
	classes_count['bg'] = 0
	class_mapping['bg'] = len(class_mapping)

C.class_mapping = class_mapping

inv_map = {v: k for k, v in class_mapping.items()}

print('Training images per class:')
pprint.pprint(classes_count)
print('Num classes (including bg) = {}'.format(len(classes_count)))
elif options.network == 'resnet50':
    from keras_frcnn import resnet as nn
    C.network = 'resnet50'
else:
    print('Not a valid model')
    raise ValueError


# check if weight path was passed via command line
if options.input_weight_path:
    C.base_net_weights = options.input_weight_path
else:
    # set the path to weights based on backend and model
    C.base_net_weights = nn.get_weight_path()

all_imgs, classes_count, class_mapping = get_data(options.train_path)

if 'bg' not in classes_count:
    classes_count['bg'] = 0
    class_mapping['bg'] = len(class_mapping)

C.class_mapping = class_mapping

inv_map = {v: k for k, v in class_mapping.items()}

print('Training images per class:')
pprint.pprint(classes_count)
print('Num classes (including bg) = {}'.format(len(classes_count)))

config_output_filename = options.config_filename
示例#3
0
                           C.num_rois,
                           nb_classes=len(class_mapping),
                           trainable=True)

model_rpn = Model(img_input, rpn_layers)
model_classifier_only = Model([feature_map_input, roi_input], classifier)

model_classifier = Model([feature_map_input, roi_input], classifier)

model_rpn.load_weights(C.model_path, by_name=True)
model_classifier.load_weights(C.model_path, by_name=True)

model_rpn.compile(optimizer='sgd', loss='mse')
model_classifier.compile(optimizer='sgd', loss='mse')

test_imgs, _, _ = get_data(options.test_path)
#test_imgs = [s for s in all_imgs if s['imageset'] == 'test']
begin = time.time()
cls_list = [
    ' seagram', ' pebriz', ' boxtape', ' cass', ' detergent', ' kantata',
    ' kechap', ' myzzo', ' papercup', ' parisredbean', ' pringles', ' sausage',
    ' seoulmilk', ' shrimpsnack', ' sunuporange', ' tunacan', ' vita500',
    ' vitajelly'
]
T = {cls: [] for cls in cls_list}
P = {cls: [] for cls in cls_list}
iou_result = 0
progbar = generic_utils.Progbar(len(test_imgs))
for idx, img_data in enumerate(test_imgs):
    #print('{}/{}'.format(idx + 1,len(test_imgs)))
    #if idx %(40*3) not in [0, 1, 2]: continue
示例#4
0
test_cls = [
    'aeroplane', 'bicycle', 'boat', 'bus', 'car', 'chair', 'diningtable',
    'motorbike', 'sofa', 'train', 'tvmonitor'
]

# turn off any data augmentation at test time
C.use_horizontal_flips = False
C.use_vertical_flips = False
C.rot_90 = False

if os.path.exists('pickle_data/mAVP_test_file.pickle'):
    with open('pickle_data/mAVP_test_file.pickle') as f:
        all_imgs, _, _ = pickle.load(f)
else:
    all_imgs, _, _ = get_data(test_path)
test_imgs = [s for s in all_imgs if s['imageset'] == 'trainval']
test_imgs.sort(key=lambda k: k['filepath'])


def format_img(img, C):
    img_min_side = float(C.im_size)
    (height, width, _) = img.shape

    if width <= height:
        f = img_min_side / width
        new_height = int(f * height)
        new_width = int(img_min_side)
    else:
        f = img_min_side / height
        new_width = int(f * width)
示例#5
0
C.use_horizontal_flips = False
C.use_vertical_flips = False
C.rot_90 = False
C.model_path = "dataset/model.hdf5"
C.num_rois = 10
C.network = 'resnet50'
C.base_net_weights = "model/resnet50_weights_tf_dim_ordering_tf_kernels.h5"
# else set the path to weights based on backend and model
# C.base_net_weights = nn.get_weight_path()
config_output_filename = "dataset/config.pickle"

epoch_length = 400
num_epochs = 30
ab_path = os.path.dirname(os.path.abspath(__file__))
all_imgs, classes_count, class_mapping = get_data(ab_path + "/dataset")

if 'bg' not in classes_count:
    classes_count['bg'] = 0
    class_mapping['bg'] = len(class_mapping)

C.class_mapping = class_mapping
#inv_map {0: 'RBC', 1: 'bg'}
#class_mapping{'RBC': 0, 'bg': 1}
inv_map = {v: k for k, v in class_mapping.items()}
print('Training images per class:')
pprint.pprint(classes_count)
print('Num classes (including bg) = {}'.format(len(classes_count)))

with open(config_output_filename, 'wb') as config_f:
    pickle.dump(C, config_f)
示例#6
0
    from keras_frcnn import vgg as nn
    print('use vgg')
elif cfg.network == 'resnet50':
    from keras_frcnn import resnet as nn
    print('use resnet50')
else:
    print('Not a valid model')
    raise ValueError

if cfg.input_weight_path:  # 这里已经被赋值为cfg里的值
    cfg.base_net_weights = cfg.input_weight_path
else:
    print('does not init')
    #raise ValueError

all_imgs, classes_count, bird_class_count = get_data(cfg.train_path,part_class_mapping)
data_lei = march.get_voc_label(all_imgs, classes_count, part_class_mapping, bird_class_count, bird_class_mapping,config= cfg,trainable=True)
#pprint.pprint(classes_count)
#pprint.pprint(part_class_mapping)
# 这里的类在match里边定义
if 'bg' not in classes_count:
    classes_count['bg'] = 0
    part_class_mapping['bg'] = len(part_class_mapping)

cfg.class_mapping = part_class_mapping


print('Training images per class:')
pprint.pprint(classes_count)
pprint.pprint(part_class_mapping)
print('Num classes (including bg) = {}'.format(len(classes_count)))
示例#7
0
if C.parser == 'pascal_voc':
    from keras_frcnn.pascal_voc_parser import get_data
elif C.parser == 'simple':
    from keras_frcnn.simple_parser import get_data
else:
    raise ValueError("Command line option parser must be one of 'pascal_voc' or 'simple'")

splits = None
# if the splits already exist, we will load them in
# delete this file if you are a different amount of pictures now
if os.path.exists(C.output_folder+"splits.pickle"):
    with open(C.output_folder+"splits.pickle", 'rb') as splits_f:
        splits = pickle.load(splits_f)


all_imgs_dict, classes_count, class_mapping = get_data(
    C.train_path, image_folder=IMAGE_FOLDER, train_test_split=splits)
all_imgs = []
for key in all_imgs_dict:
    all_imgs.append(all_imgs_dict[key])

if 'bg' not in classes_count:
    classes_count['bg'] = 0
    class_mapping['bg'] = len(class_mapping)

C.class_mapping = class_mapping
C.classes_count = classes_count
# inv_map = {v: k for k, v in class_mapping.items()}

print('Training images per class:')
pprint.pprint(classes_count)
print('Num classes (including bg) = {}'.format(len(classes_count)))
示例#8
0
elif options.network == 'resnet50':
	from keras_frcnn import resnet_rgbt as nn
	C.network = 'resnet50'
else:
	print('Not a valid model')
	raise ValueError


# check if weight path was passed via command line
if options.input_weight_path:
	C.base_net_weights = options.input_weight_path
else:
	# set the path to weights based on backend and model
	C.base_net_weights = nn.get_weight_path()

all_train_imgs, classes_count, class_mapping = get_data(options.train_path, 'train')
all_val_imgs, val_classes_count, val_class_mapping = get_data(options.train_path, 'test')

if 'bg' not in classes_count:
	classes_count['bg'] = 0
	class_mapping['bg'] = len(class_mapping)

if 'bg' not in val_classes_count:
	val_classes_count['bg'] = 0
	val_class_mapping['bg'] = len(class_mapping)


C.class_mapping = class_mapping

inv_map = {v: k for k, v in class_mapping.items()}
示例#9
0
    from keras_frcnn import vgg as nn
if options.network == 'resnet50':
    C.network = 'resnet50'
    from keras_frcnn import resnet as nn
else:
    print('No valid model')
    raise ValueError

# 检查权重文件是否来自命令行
if options.input_weight_path:
    C.base_net_weights = options.input_weight_path
else:
    C.base_net_weights = nn.get_weight_path()

# 读取voc数据集的所有图片,类别统计,类的映射
all_imgs, classes_count, class_mapping = get_data('')
# 若没有背景类,向里面添加背景类
if 'bg' not in classes_count:
    classes_count['bg'] = 0
    # 背景所在的类别映射是最大的
    class_mapping = len(classes_count)

C.class_mapping = class_mapping
# 以列表返回可遍历的(键, 值) 元组数组
inv_class_mapping = {v: k for k, v in class_mapping.items()}
print('Training_imgs per class:')
pprint.pprint(classes_count)
print('Num classes(bg) = {}'.format(len(classes_count)))

# open打开文件,默认是只读模式,现在是写模式
# pickle.dump:将对象obj保存到文件file中去
示例#10
0
def work(path, curelist, textedit):
    #print("I'm hearing too")
    #textedit.append("I'm hearing too")
    sys.setrecursionlimit(40000)
    test_path = path

    parser = OptionParser()

    parser.add_option("-p",
                      "--path",
                      dest="test_path",
                      help="Path to test data.",
                      default=test_path)
    parser.add_option(
        "-n",
        "--num_rois",
        dest="num_rois",
        help="Number of ROIs per iteration. Higher means more memory use.",
        default=256)
    parser.add_option(
        "--config_filename",
        dest="config_filename",
        help=
        "Location to read the metadata related to the training (generated when training).",
        default="config.pickle")
    parser.add_option("-o",
                      "--parser",
                      dest="parser",
                      help="Parser to use. One of simple or pascal_voc",
                      default="pascal_voc"),  #default="pascal_voc"

    (options, args) = parser.parse_args()

    if not options.test_path:  # if filename is not given
        parser.error(
            'Error: path to test data must be specified. Pass --path to command line'
        )

    if options.parser == 'pascal_voc':
        from keras_frcnn.pascal_voc_parser import get_data
    elif options.parser == 'simple':
        from keras_frcnn.simple_parser import get_data
    else:
        raise ValueError(
            "Command line option parser must be one of 'pascal_voc' or 'simple'"
        )

    config_output_filename = options.config_filename

    with open(config_output_filename, 'rb') as f_in:
        C = pickle.load(f_in)

    # turn off any data augmentation at test time
    C.use_horizontal_flips = False
    C.use_vertical_flips = False
    C.rot_90 = False

    img_path = options.test_path

    class_mapping = C.class_mapping

    if 'bg' not in class_mapping:
        class_mapping['bg'] = len(class_mapping)

    #class_mapping = {v: k for k, v in class_mapping.iteritems()}
    class_mapping = {v: k for k, v in class_mapping.items()}
    print(class_mapping)
    class_to_color = {
        class_mapping[v]: np.random.randint(0, 255, 3)
        for v in class_mapping
    }
    C.num_rois = int(options.num_rois)

    if K.image_dim_ordering() == 'th':
        input_shape_img = (3, None, None)
        input_shape_features = (1024, None, None)
    else:
        input_shape_img = (None, None, 3)
        input_shape_features = (None, None, 1024)

    img_input = Input(shape=input_shape_img)
    roi_input = Input(shape=(C.num_rois, 4))
    feature_map_input = Input(shape=input_shape_features)

    # define the base network (resnet here, can be VGG, Inception, etc)
    shared_layers = nn.nn_base(img_input, trainable=True)

    # define the RPN, built on the base layers
    num_anchors = len(C.anchor_box_scales) * len(C.anchor_box_ratios)
    rpn_layers = nn.rpn(shared_layers, num_anchors)

    classifier = nn.classifier(feature_map_input,
                               roi_input,
                               C.num_rois,
                               nb_classes=len(class_mapping),
                               trainable=True)

    model_rpn = Model(img_input, rpn_layers)
    model_classifier_only = Model([feature_map_input, roi_input], classifier)

    model_classifier = Model([feature_map_input, roi_input], classifier)

    model_rpn.load_weights(C.model_path, by_name=True)
    model_classifier.load_weights(C.model_path, by_name=True)

    model_rpn.compile(optimizer='sgd', loss='mse')
    model_classifier.compile(optimizer='sgd', loss='mse')

    #####
    all_imgs, _, _ = get_data(options.test_path)
    test_imgs = [s for s in all_imgs if s['imageset'] == 'test']

    #test_imgs=test_imgs1[3111:4056]

    T = {}
    P = {}
    for idx, img_data in enumerate(test_imgs):
        print('{}/{}'.format(idx, len(test_imgs)))
        #textedit.append('{}/{}'.format(idx,len(test_imgs)))

        st = time.time()
        filepath = img_data['filepath']
        print(filepath)
        img = cv2.imread(filepath)

        X, fx, fy = format_img(img, C)

        if K.image_dim_ordering() == 'tf':
            X = np.transpose(X, (0, 2, 3, 1))

        # get the feature maps and output from the RPN
        [Y1, Y2, F] = model_rpn.predict(X)

        R = roi_helpers.rpn_to_roi(Y1,
                                   Y2,
                                   C,
                                   K.image_dim_ordering(),
                                   overlap_thresh=0.5)  ##0.7

        # convert from (x1,y1,x2,y2) to (x,y,w,h)
        R[:, 2] -= R[:, 0]
        R[:, 3] -= R[:, 1]

        # apply the spatial pyramid pooling to the proposed regions
        bboxes = {}
        probs = {}

        for jk in range(R.shape[0] // C.num_rois + 1):
            ROIs = np.expand_dims(R[C.num_rois * jk:C.num_rois * (jk + 1), :],
                                  axis=0)
            if ROIs.shape[1] == 0:
                break

            if jk == R.shape[0] // C.num_rois:
                # pad R
                curr_shape = ROIs.shape
                target_shape = (curr_shape[0], C.num_rois, curr_shape[2])
                ROIs_padded = np.zeros(target_shape).astype(ROIs.dtype)
                ROIs_padded[:, :curr_shape[1], :] = ROIs
                ROIs_padded[0, curr_shape[1]:, :] = ROIs[0, 0, :]
                ROIs = ROIs_padded

            [P_cls, P_regr] = model_classifier_only.predict([F, ROIs])

            for ii in range(P_cls.shape[1]):

                if np.argmax(P_cls[0, ii, :]) == (P_cls.shape[2] - 1):
                    continue

                cls_name = class_mapping[np.argmax(P_cls[0, ii, :])]

                if cls_name not in bboxes:
                    bboxes[cls_name] = []
                    probs[cls_name] = []

                (x, y, w, h) = ROIs[0, ii, :]

                cls_num = np.argmax(P_cls[0, ii, :])
                try:
                    (tx, ty, tw, th) = P_regr[0, ii,
                                              4 * cls_num:4 * (cls_num + 1)]
                    tx /= C.classifier_regr_std[0]
                    ty /= C.classifier_regr_std[1]
                    tw /= C.classifier_regr_std[2]
                    th /= C.classifier_regr_std[3]
                    x, y, w, h = roi_helpers.apply_regr(
                        x, y, w, h, tx, ty, tw, th)
                except:
                    pass
                bboxes[cls_name].append(
                    [16 * x, 16 * y, 16 * (x + w), 16 * (y + h)])
                probs[cls_name].append(np.max(P_cls[0, ii, :]))

        all_dets = []

        for key in bboxes:
            bbox = np.array(bboxes[key])

            new_boxes, new_probs = roi_helpers.non_max_suppression_fast(
                bbox, np.array(probs[key]), overlap_thresh=0.45)  ###0.5
            for jk in range(new_boxes.shape[0]):
                (x1, y1, x2, y2) = new_boxes[jk, :]
                det = {
                    'x1': x1,
                    'x2': x2,
                    'y1': y1,
                    'y2': y2,
                    'class': key,
                    'prob': new_probs[jk]
                }
                all_dets.append(det)

        print('Elapsed time = {}'.format(time.time() - st))
        cursor = textedit.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText('{}/{}'.format(idx, len(test_imgs)))
        cursor.insertText("\r\n")
        cursor.insertText('Elapsed time = {}'.format(time.time() - st))
        cursor.insertText("\r\n")
        # textedit.append('Elapsed time = {}'.format(time.time() - st))
        textedit.setTextCursor(cursor)
        textedit.ensureCursorVisible()

        t, p = get_map(all_dets, img_data['bboxes'], (fx, fy))
        for key in t.keys():
            if key not in T:
                T[key] = []
                P[key] = []
            T[key].extend(t[key])
            P[key].extend(p[key])
    p1 = []
    t1 = []
    p1.append(P["airbase"])
    t1.append(T["airbase"])

    p1.append(P["harbour"])
    t1.append(T["harbour"])

    p1.append(P["island"])
    t1.append(T["island"])

    prefastr = []
    recfastr = []
    apfastr = []

    for m in range(len(p1)):
        p11 = np.zeros(len(p1[m]))
        for i in range(len(p1[m])):
            if p1[m][i] > 0.45:
                p11[i] = 1
            else:
                p11[i] = 0
        p_p1 = p11
        t_t1 = t1[m]

        false_positives = np.zeros((0, ))
        true_positives = np.zeros((0, ))
        scores = np.zeros((0, ))
        num_annotations = 0.0
        nump = len(p_p1)

        # for n in range (1915):#(len(p_p1)):
        for n in range(len(p_p1)):
            if t_t1[n] == 1 and p_p1[n] == 1:
                true_positives = np.append(true_positives, 1)
                false_positives = np.append(false_positives, 0)
                scores = np.append(scores, p1[m][n])

            if t_t1[n] == 0 and p_p1[n] == 1:
                true_positives = np.append(true_positives, 0)
                false_positives = np.append(false_positives, 1)
                scores = np.append(scores, p1[m][n])

            # if t_t1[n]==1 and p_p1[n]==0:
            #   true_positives = np.append(true_positives, 0)
            #  false_positives = np.append(false_positives, 0)
            # scores = np.append(scores, p1[m][n])

            if t_t1[n] == 1:
                num_annotations = num_annotations + 1

        descending_indices = np.argsort(-scores)
        true_positives = true_positives[descending_indices]
        false_positives = false_positives[descending_indices]

        # compute false positives and true positives
        true_positives = np.cumsum(true_positives)
        false_positives = np.cumsum(false_positives)

        # compute recall and precision
        recall1 = true_positives / num_annotations
        precision1 = true_positives / np.maximum(
            true_positives + false_positives,
            np.finfo(np.float64).eps)

        average_precision = compute_ap(recall1, precision1)

        prefastr.append(precision1)
        recfastr.append(recall1)
        apfastr.append(average_precision)
    for i in range(0, len(recfastr)):
        curelist[i].setData(recfastr[i], prefastr[i])
示例#11
0
    print('use resnet50')
# cfg.network = 'resnet50'
else:
    print('Not a valid model')
    raise ValueError
# 使用restnet网络

# check if weight path was passed via command line
if cfg.input_weight_path:  # 这里已经被赋值为cfg里的值
    cfg.base_net_weights = cfg.input_weight_path
else:
    # set the path to weights based on backend and model
    cfg.base_net_weights = nn.get_weight_path()
# 设定restore路径

all_imgs, classes_count, class_mapping, bird_class_count, bird_class_mapping = get_data(
    cfg.train_path)  # get_data函数在pascalvocparser.py里变

if 'bg' not in classes_count:
    classes_count['bg'] = 0
    class_mapping['bg'] = len(class_mapping)

cfg.class_mapping = class_mapping

inv_map = {v: k for k, v in class_mapping.items()}

print('Training images per class:')
pprint.pprint(classes_count)
print('Num classes (including bg) = {}'.format(len(classes_count)))
print('Training bird per class:')
pprint.pprint(bird_class_count)
print('total birds class is {}'.format(len(bird_class_count)))
示例#12
0
import random
import pprint
import sys
import json
from keras_frcnn import config

sys.setrecursionlimit(40000)

C = config.Config()
C.num_rois = 8

from keras_frcnn.pascal_voc_parser import get_data

all_imgs, classes_count, class_mapping = get_data(sys.argv[1])

if 'bg' not in classes_count:
    classes_count['bg'] = 0
    class_mapping['bg'] = len(class_mapping)

with open('classes.json', 'w') as class_data_json:
    json.dump(class_mapping, class_data_json)

inv_map = {v: k for k, v in class_mapping.iteritems()}

pprint.pprint(classes_count)

random.shuffle(all_imgs)

num_imgs = len(all_imgs)

train_imgs = [s for s in all_imgs if s['imageset'] == 'trainval']
示例#13
0
rpn_layers = nn.rpn(shared_layers, num_anchors)

classifier = nn.classifier(feature_map_input, roi_input, C.num_rois, nb_classes = len(class_mapping), trainable = False)

model_rpn = Model(img_input, rpn_layers)
model_classifier = Model([feature_map_input, roi_input], classifier)

C.model_path = model_path

model_rpn.load_weights(C.model_path, by_name = True)
model_classifier.load_weights(C.model_path, by_name = True)

model_rpn.compile(optimizer = 'sgd', loss = 'mse')
model_classifier.compile(optimizer = 'sgd', loss = 'mse')

all_imgs, _, _ = get_data(options.data_path)
test_imgs = [s for s in all_imgs if s['imageset'] == options.file_type]

if len(test_imgs) == 0:
    raise NameError('No images to process. Verify the path to testing images file and file_type parameter.')

print("Number of images to process: {}".format(len(test_imgs)))
print("============ Starting Detections ============")

T = {}
P = {}
st = time.time()
for idx, img_data in enumerate(test_imgs):

    if idx % 100 == 0 and idx > 0:
        print('================== {}/{} =================='.format(idx, len(test_imgs)))