Пример #1
0
def process():
    session = getUserInSession()
    ext = request.form.get('ext')
    #dropping table with the same number as the current session has if it somehow exists
    engine = create_engine(db_url)
    sql = text('DROP TABLE IF EXISTS table_' + session + ';')
    engine.execute(sql)

    #calling tracker from cmd that may be not correct (perhaps having the entire tracker code as an imported module would be better)
    dir_path = os.path.dirname(os.path.realpath(__file__))
    os.chdir(dir_path)
    os.system(
        "conda activate project & python object_tracker.py --video static/" +
        session + "." + ext + " --output data/video/output.mp4")

    #calling text detector
    start.main(project_path + "static/" + session + "/",
               project_path + "static/" + session + "/")

    #calling text recogniser, 2nd parameter helps us to get db name etc
    demo.main(project_path + "static/" + session + "/",
              len(project_path) + 7, db_url)

    #reading table and writing data to html
    df = read_table(session, engine)
    write_html('templates/' + session + '.html', df)
    df.to_excel('static/' + session + '/results.xlsx')
    return render_template(session + ".html")
def run_demo(picked_datasets_index):
    # First clear some folders
    remove_folder_content(demo_input_path)
    remove_folder_content(demo_output_path)

    # Now pick some random images from dataset
    random_files = []
    folder_path = datasets[picked_datasets_index]
    for _ in range(files_to_pick):
        random_files.append(folder_path + "/" +
                            random.choice(os.listdir(folder_path)))

    for random_file in random_files:
        shutil.copy2(random_file, demo_input_path)

    # Now generate names for them
    generate_demo_file_names.main()

    import demo
    demo.main()

    # Now save results with renamed name to results folder
    results_folder = '../results'
    N = 10
    file_index = 0
    for file in os.listdir(demo_output_path):
        # 0 - gt
        # 1 - black and white
        # 2 - out
        file_extension = file.split('.')[-1]
        if file_index % 3 == 0:
            dataset_name = datasets[picked_datasets_index].split('/')[-1]
            random_name = ''.join(
                random.choices(string.ascii_uppercase + string.digits, k=N))
            gt = f"{random_name}_gt.{file_extension}"
            bandw = f"{random_name}_black_and_white.{file_extension}"
            out = f"{random_name}_out.{file_extension}"

            shutil.copy2(f"{demo_output_path}/{file}",
                         f"{results_folder}/{dataset_name}/{gt}")
        elif file_index % 3 == 1:
            # Black and white
            shutil.copy2(f"{demo_output_path}/{file}",
                         f"{results_folder}/{dataset_name}/{bandw}")
        else:
            # out
            shutil.copy2(f"{demo_output_path}/{file}",
                         f"{results_folder}/{dataset_name}/{out}")

        file_index += 1
Пример #3
0
def models2df(model_names, opt, save_dir=None):
    """
    Applies provided models to provided stimuli and outputs network activation
    data as a DataFrame for further processing.
    """
    activation_data = []
    columns = [
        "StimulusName", "ImageMode", "ModelName", "Region", "Activations"
    ]

    for img_mode in opt.feeding_modes:
        stim_source, mode = str.split(img_mode, "-")
        img_paths = []
        if stim_source == "original":
            img_dir = opt.stimuli_dir
            img_paths = sorted(os.listdir(img_dir))
        elif stim_source == "rendered":
            if os.path.exists(opt.stimuli_dir + '-trunk-centric'):
                img_dir = opt.stimuli_dir + "-trunk-centric"
            else:
                img_dir = opt.stimuli_dir + "-trunk-centric-uncentered"
            img_paths = sorted(os.listdir(img_dir))
            img_paths = [path for path in img_paths if "-" not in path]
        else:
            print(
                "Source in image mode {} is not implemented.".format(img_mode))

        # loop through all stimuli/images in this mode
        make_path('tmp')
        for img_path in img_paths:
            stimulus_name = str.split(os.path.basename(img_path), ".")[0]

            # loop through image modes (e.g. "raw" or "cropped")
            if mode == "raw":
                img_path = os.path.join(img_dir, img_path)
            elif mode == "cropped":
                img_path = os.path.join(img_dir + '-cropped', img_path)
            # elif mode == "attended":
            #     img = attend_crop_img(img, attend_size=opt.attend_size)
            else:
                print("Mode in image mode {} is not implemented.".format(mode))

            # loop through models
            for model_name in model_names:
                print('\nComputing output for model {} and image {}.\n'.format(
                    model_name, stimulus_name))
                output = main(img_path, model_type=model_name)
                # loop through labels
                for model_region in opt.model_regions[model_name]:
                    out = output[model_region].flatten()
                    activation_data.append([
                        stimulus_name, img_mode, model_name, model_region, out
                    ])

    return pd.DataFrame(activation_data, columns=columns)
Пример #4
0
def main(file_list = ["PID026.JPG"]):
    from time import clock

    predicted_symbols, classes, size = Dectection.main(file_list, DEBUG)

    ret_list = []
    t_start = clock()
    for item in zip(predicted_symbols, file_list):
        keys = item[0].keys()
        img = Image.open(item[1])
        coordinate_list = []
        #draw = ImageDraw.Draw(img)eog
        if 0 in keys:
            for bound in item[0][0]: #Valve
                symbol_dict = {}
                coordinate = bound[0]
                symbol_dict['coord'] = coordinate
                symbol_dict['type'] = 0
                img_cv = PIL2CV(img.crop(coordinate))
                #Feature_matching(img_cv)
                symbol_dict['detail'] = Specific_Valve(img_cv)
                if symbol_dict['detail'] is None:
                    symbol_dict['detail'] = "None"
                coordinate_list.append(symbol_dict)
        if 2 in keys:
            for bound in item[0][2]:
                symbol_dict = {}
                coordinate = bound[0]
                symbol_dict['coord'] = coordinate
                symbol_dict['type'] = 2
                symbol_dict['detail'] = "None"
                coordinate_list.append(symbol_dict)
        if 1 in keys: #
            for bound in item[0][1]:
                symbol_dict = {}
                coordinate = bound[0]
                symbol_dict['coord'] = coordinate
                symbol_dict['type'] = 1
                for i in range(9, 3, -1):
                    temp = []
                    image_cv = convert_PIL_cv(img,coordinate,i)
                    OCR_str = pytesseract.image_to_string(image_cv, config=tess_CONFIG)
                    if len(OCR_str) != 1:
                        OCR_str = OCR_str.replace(' ','').split("\n")
                        temp = _OCR_string(OCR_str[0])
                        if len(OCR_str) != 1:
                            temp += _OCR_digit(OCR_str[1])
                        if len(temp) !=0:

                            break
                symbol_dict['detail'] = temp
                coordinate_list.append(symbol_dict)
        ret_list.append(coordinate_list)
    print("Execution Time : {}".format(clock() - t_start))
    return ret_list, classes
Пример #5
0
def main():
    """Starts the application and creates a virtualenv in case of failure."""
    _dir, _script = osp.split(osp.abspath(__file__))
    _venv = osp.join(_dir, 'venv')
    _bin = osp.join(_venv, 'Scripts' if sys.platform == 'win32' else 'bin')
    _py = osp.join(_bin, 'python')

    try:
        # We try to import our application module
        import demo
    except ImportError:
        # Our application fails to import dependencies
        if not osp.exists(_venv):
            # Creates a virtual environment and installs
            # dependencies using pip
            venv.create(_venv, with_pip=True)
            pip.main(['install', '-r', 'requirements.txt', '--prefix', _venv])
        # Execute the script with the venv python executable
        subprocess.run([_py, _script])
    else:
        demo.main()
Пример #6
0
 def stopRecording(self):
     self.out.release()
     self.capture = not self.capture
     self.btn_snapshot["text"] = "Record"
     self.class_label["text"] = "Loading label"
     # self.playSound(self.class_label["text"])
     print("Should extract")
     extract_files.extract_file()
     print("extraction done")
     prediction = demo.main()
     self.playSound(prediction)
     self.class_label["text"] = prediction
Пример #7
0
def main(_):
    trainig_folder = setup_logging_and_exp_folder()
    FLAGS.cuda = FLAGS.cuda and torch.cuda.is_available()
    logging.info('Use Cuda: {}'.format(FLAGS.cuda))
    logging.info('Current git SHA: ' + CURR_VERSION)

    # save options
    fpath = os.path.join(trainig_folder, 'flagfile')
    with open(fpath, 'w') as f:
        f.write(FLAGS.flags_into_string())

    if FLAGS.mode == 'IL':
        IL.run(training_folder=trainig_folder)
    elif FLAGS.mode == 'demo':
        demo.main()
    elif FLAGS.mode == 'compile':
        train_compile.main(training_folder=trainig_folder)
    elif FLAGS.mode == 'taco':
        train_taco.main(training_folder=trainig_folder)
    else:
        logging.fatal('Improper Mode {}'.format(FLAGS.mode))
    logging.info('Done')
Пример #8
0
def score():
    #print("请求已开始")
    #theimg1 = str(json.loads(request.values.get("theimg1")))
    #theimg2=str(json.loads(request.values.get("theimg2")))
    theimg1 = str(json.loads(request.values.get("temp1")))
    theimg2 = str(json.loads(request.values.get("temp2")))
    img1 = base64.b64decode(theimg1)
    img2 = base64.b64decode(theimg2)
    f1 = open(
        'E:/meizhuanghouduan/PSGAN/assets/images/non-makeup/xfsy_0106.png',
        'wb')
    f1.write(img1)
    f1.close()
    f2 = open('E:/meizhuanghouduan/PSGAN/assets/images/makeup/makeup.png',
              'wb')
    f2.write(img2)
    f2.close()
    demo.main()
    f = open('E:/meizhuanghouduan/transferred_image.png', 'rb')
    img = base64.b64encode(f.read()).decode('utf-8')
    f.close()
    #res='返回成功'
    print("文件已加载")
    return json.dumps(img)
Пример #9
0
    def __init__(self, *args, **kw):
        info = main()
        info_string = ""
        for line in info:
            info_string += str(line)
            info_string += "\n"

        super(HelloFrame, self).__init__(*args, **kw)
        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)
        st = wx.StaticText(pnl, label=info_string, style=wx.ALIGN_LEFT)
        font = wx.Font(10, wx.ROMAN, wx.NORMAL, wx.NORMAL)
        st.SetFont(font)
        vbox.Add(st, flag=wx.ALL, border=15)
        pnl.SetSizer(vbox)

        self.Centre()
        self.SetSize((800, 800))
        self.makeMenuBar()
        self.CreateStatusBar()
        self.SetStatusText("Welcome to wxPython!")
if __name__ == "__main__":
    # solver_init()
    cfg_from_list(['CONST.BATCH_SIZE', 1])
    for checkpoint_dir, pre_dir, model_name in zip(Checkpoint_dir, Pre_dir,
                                                   Model_names):
        # print(checkpoint_dir, pre_dir)
        weights = os.path.join(checkpoint_dir, 'checkpoint.tar')
        set_weights(weights)
        set_model_name(model_name)

        # if pre_dir == './prediction/ResidualGRUNet_No_Regularition/':
        #     cfg_from_list(['TEST.VOXEL_THRESH', [0.4]])

        for index in range(1, 11):
            checkpoint_path = os.path.join(
                checkpoint_dir, 'checkpoint.%d.tar' % (index * 2000))
            # print(save_path)
            symlink_path = os.path.join(checkpoint_dir, 'checkpoint.tar')
            if os.path.lexists(symlink_path):
                os.remove(symlink_path)
            os.symlink("%s" % os.path.abspath(checkpoint_path), symlink_path)

            # set_pred_file_name
            name = os.path.join(pre_dir, 'prediction.%d.obj' % (index * 2000))

            set_pred_file_name(name)

            main()
            # Make a symlink to the latest network params
            # os.symlink("%s" % os.path.abspath(checkpoint_path), symlink_path)
Пример #11
0
import demo

if __name__ == "__main__":
    demo.main()
Пример #12
0
def script_call():
    return redirect(demo.main(app.config['SRC']))
Пример #13
0
    mask_input[np.where(np.logical_and(mask_input == -1,
                                       np.logical_or(result >= 2.5,
                                                     target >= 2.5)))] = 0
    tracker2 = IndexTracker(ax2, mask_input)
    fig.canvas.mpl_connect('scroll_event', tracker2.onscroll)

    ax3 = fig.add_subplot(223)
    ax3.set_title('Prediction')
    tracker3 = IndexTracker(ax3, result)
    fig.canvas.mpl_connect('scroll_event', tracker3.onscroll)

    if target is not None:
        ax4 = fig.add_subplot(224)
        ax4.set_title('Target')
        tracker4 = IndexTracker(ax4, target)
        fig.canvas.mpl_connect('scroll_event', tracker4.onscroll)

    plt.tight_layout()
    plt.show()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Slicer')
    parser.add_argument('--model', type=str, default='../models/checkpoint.pth',
                        help='trained model path')
    parser.add_argument('--input', type=str, default='../datasets/sample/overfit.h5',
                        help='uses file as input')
    args = parser.parse_args()

    main(args.model, args.input, n_samples=1, cb=plot_slicer)
Пример #14
0
#
#print("back type = ",type(back))
#print("image type = ",type(np.asarray(image)))
#print("masksDL type = ",type(255*mask_sel.astype(np.uint8)))
#
#
#print("back shape = ", back.shape)
#print("image shape = ",np.asarray(image).shape)
#print("masksDL shape = ",255*mask_sel.astype(np.uint8).shape)

#back_align = alignImages(back, np.asarray(image), cv2.cvtColor(255*mask_sel.astype(np.uint8),cv2.COLOR_GRAY2RGB))

#bg_removed = remove_bg(np.asarray(image), back_align,cv2.cvtColor(255*mask_sel.astype(np.uint8),cv2.COLOR_GRAY2RGB))

#config = flags.FLAGS
#config(sys.argv)

# Using pre-trained model, change this to use your own.
#config.load_path = src.config.PRETRAINED_MODEL
#
#config.batch_size = 1

#cv2.imwrite(dir_name.replace('img','back'),remove_bg)
main(bg_removed, args.height, None)
#name= dir_name.replace('img','masksDL')
#cv2.imwrite(name,(255*mask_sel).astype(np.uint8))
#cv2.imwrite(dir_name.replace('img','back'),back_align)

#str_msg='\nDone: ' + dir_name
#print(str_msg)
Пример #15
0
def test_main():
    main()
Пример #16
0
def modify_doc(doc):
    demo.main(doc)
Пример #17
0
import demo

demo.main()
def test_demo(args: List[str]):
    demo.main(demo.parser.parse_args(args))
Пример #19
0
def test_runs():
    demo.main()
#
#print("back type = ",type(back))
#print("image type = ",type(np.asarray(image)))
#print("masksDL type = ",type(255*mask_sel.astype(np.uint8)))
#
#
#print("back shape = ", back.shape)
#print("image shape = ",np.asarray(image).shape)
#print("masksDL shape = ",255*mask_sel.astype(np.uint8).shape)

#back_align = alignImages(back, np.asarray(image), cv2.cvtColor(255*mask_sel.astype(np.uint8),cv2.COLOR_GRAY2RGB))

#bg_removed = remove_bg(np.asarray(image), back_align,cv2.cvtColor(255*mask_sel.astype(np.uint8),cv2.COLOR_GRAY2RGB))

#config = flags.FLAGS
#config(sys.argv)

# Using pre-trained model, change this to use your own.
#config.load_path = src.config.PRETRAINED_MODEL
#
#config.batch_size = 1

#cv2.imwrite(dir_name.replace('img','back'),remove_bg)
main(bg_removed, None)
#name= dir_name.replace('img','masksDL')
#cv2.imwrite(name,(255*mask_sel).astype(np.uint8))
#cv2.imwrite(dir_name.replace('img','back'),back_align)

#str_msg='\nDone: ' + dir_name
#print(str_msg)
Пример #21
0
from demo import main 

main(['walWalkNext', 'NK', 'rLS', 'fit', '0', '1', '10', '2', '0'])
#main(['walWalkNext', 'NK', 'rLS', 'fit', '0', '1', '1000', '2', '0'])
#main(['walWalkNext', 'NK', 'rLS', 'fit', '0', '1', '1000', '4', '0'])
#main(['walWalkNext', 'NK', 'rLS', 'fit', '0', '1', '1000', '8', '0'])