Exemplo n.º 1
0
def testing_load():
    global server_testing_internal
    plan = flask.request.args.get("plan")
    print(plan)
 
    server_testing_internal = {
        'plans': [],
        'groups': [],
        'nets': [],
        'metas': []
    }

    try:
        url = 'http://localhost:8800/api/Training/plan?plan=%s' % plan
        response = requests.get(url)
        plan_json = response.json()
        training_metas = get_ar_plan.get_training_metas(plan_json)

        for training_meta in training_metas:
            folder = training_meta['folder']
            obj_cfg = join(folder, 'obj.cfg')
            obj_weights = join(folder, 'weights/obj_final.weights')
            obj_names = join(folder, 'obj.names')
            if not os.path.exists(obj_cfg):
                raise Exception('%s missing' % obj_cfg)
            if not os.path.exists(obj_weights):
                raise Exception('%s missing' % obj_weights)
            if not os.path.exists(obj_names):
                raise Exception('%s missing' % obj_names)

            net, meta = lightnet.load_network_meta(obj_cfg, obj_weights, obj_names)
            server_testing_internal['plans'].append(training_meta['plan'])
            server_testing_internal['groups'].append(training_meta['group'])
            server_testing_internal['nets'].append(net)
            server_testing_internal['metas'].append(meta)
        result = {
                'errCode': 'OK', # or 'Error'
                'errMsg': ''
            }
    except:
        error_callstack = traceback.format_exc()
        print(error_callstack)
        result = {
            'errCode': 'Error', # or 'Error'
            'errMsg': error_callstack
        }
    
    return flask.jsonify(result)
Exemplo n.º 2
0
def main():
    # lightnet.set_cwd(dir)
    global nets, metas, args, cap

    def add_bool_arg(parser, name, default=False):
        group = parser.add_mutually_exclusive_group(required=False)
        group.add_argument('--' + name, dest=name, action='store_true')
        group.add_argument('--no-' + name, dest=name, action='store_false')
        parser.set_defaults(**{name: default})

    parser = argparse.ArgumentParser()
    parser.add_argument('--cfg', default='obj.cfg')
    parser.add_argument('--weights', default='weights/obj_last.weights')
    parser.add_argument('--names', default='obj.names')
    parser.add_argument('--valid_csv')
    parser.add_argument('--image')
    parser.add_argument('--video')
    parser.add_argument('--socket', type=int)
    parser.add_argument('--camera', type=int, default=0)
    parser.add_argument('--top_k', type=int, default=5)
    parser.add_argument('--gold_confidence', type=float, default=0.95)
    parser.add_argument('--threshold', type=float, default=0.5)
    add_bool_arg(parser, 'debug')
    add_bool_arg(parser, 'yolo', True)
    add_bool_arg(parser, 'interactive')

    args = parser.parse_args()
    args_cfgs = args.cfg.split(',')
    args_weights = args.weights.split(',')
    args_names = args.names.split(',')
    for i, _ in enumerate(args_cfgs):
        net, meta = lightnet.load_network_meta(args_cfgs[i], args_weights[i],
                                               args_names[i])
        nets.append(net)
        metas.append(meta)

    logging.basicConfig(level=logging.INFO)

    if args.debug:
        folder_name = 'socket_debug'
        if not os.path.exists(folder_name):
            os.mkdir(folder_name)

        # create a file handler
        handler = logging.FileHandler('socket_debug/debug.log')
        handler.setLevel(logging.INFO)
        # create a logging format
        formatter = logging.Formatter('%(asctime)s - %(thread)d - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)

        global csv_file
        now = datetime.datetime.now()
        now_string = now.strftime("%Y-%h-%d-%H-%M-%S-%f")
        csv_name = 'socket_debug' + '/' + now_string + '.csv'
        csv_file = open(csv_name, 'w')
        csv_file.write('image')
        for i, _ in enumerate(args_cfgs):
            csv_file.write(',%d_top1,score,%d_top2,score,%d_top3,score' %
                           (i + 1, i + 1, i + 1))
        csv_file.flush()
        csv_file.write('\n')

    if args.socket:

        # flask routine
        print('=========================================')
        get_Host_name_IP()
        print('=========================================')
        app.run(host='0.0.0.0', port=args.socket, threaded=True)
        exit(0)

    if args.valid_csv:
        validate_run()
        return
    elif args.interactive:
        interactive_run()
        return
    elif args.video or args.image:
        media = args.image
        if not media:
            media = args.video
        cap = cv.VideoCapture(media)
        if not cap.isOpened():
            raise Exception('Fail to open %s' % media)
    else:
        cap = cv.VideoCapture(args.camera)
        if not cap.isOpened():
            raise Exception('Fail to open camera %d' % args.camera)

    local_app_run()
Exemplo n.º 3
0
parser.add_argument('--yolo_cfg')
parser.add_argument('--yolo_weights')

args = parser.parse_args()
args.images = pathlib.Path(args.images).as_posix()
cwd = os.getcwd()

# initialize OpenCV's static fine grained saliency detector and
# compute the saliency map
saliency = cv.saliency.StaticSaliencyFineGrained_create()

W = 448
H = 448

if args.yolo_cfg:
    yolo_net, yolo_meta = lightnet.load_network_meta(
        args.yolo_cfg, args.yolo_weights)


def process(category):
    image_filenames = glob.glob('%s/*.png' % (category), recursive=True)
    image_filenames.extend(glob.glob('%s/*.jpg' % (category), recursive=True))
    # print("Start category: %s" % (category))
    for filename in image_filenames:
        # load the input image
        filename = pathlib.Path(filename).as_posix()
        image = cv.imread(filename)
        h, w, c = image.shape

        # roi
        if False:
            x_spacing = 20
Exemplo n.º 4
0
import sys
import os

dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(dir, '../bin'))

import lightnet

if __name__ == "__main__":
    lightnet.set_cwd(dir)
    net, meta = lightnet.load_network_meta("obj.cfg",
                                           "weights/obj_200.weights",
                                           "obj.data")

    r = lightnet.detect_from_file(net,
                                  meta,
                                  "img/air1.jpg",
                                  thresh=0.25,
                                  debug=False)
    print(r)
Exemplo n.º 5
0
if __name__ == "__main__":
    # lightnet.set_cwd(dir)

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', default='obj.cfg')
    parser.add_argument('--weights', default='weights/obj_200.weights')
    parser.add_argument('--data', default='obj.data')
    parser.add_argument('--image')
    parser.add_argument('--video')
    parser.add_argument('--camera', type=int, default=0)
    parser.add_argument('--top_k', type=int, default=3)
    parser.add_argument('--gold_confidence', type=float, default=0.95)
    parser.add_argument('--display_confidence', type=float, default=0.5)
    args = parser.parse_args()

    net, meta = lightnet.load_network_meta(args.config, args.weights,
                                           args.data)

    if args.image is not None:
        if True:
            frame = cv.imread(lightnet.to_str('test.jpg'))
            im, arr = darknet.array_to_image(frame)
            darknet.rgbgr_image(im)
        else:
            im = darknet.load_image(lightnet.to_str('test.jpg', True), 0, 0)

        r = darknet.classify(net, meta, im)
        print(r)
    else:
        cap = cv.VideoCapture(args.camera)
        if not cap.isOpened():
            raise Exception('Fail to open %s' % (0))