Beispiel #1
0
	def __init__(self, win):
		ttk.Frame.__init__(self, win)
		frame_left = ttk.Frame(self)
		frame_right1 = ttk.Frame(self)
		frame_right2 = ttk.Frame(self)
		win.title("车牌识别")
		win.state("zoomed")
		self.pack(fill=tk.BOTH, expand=tk.YES, padx="5", pady="5")
		frame_left.pack(side=LEFT,expand=1,fill=BOTH)#grid分区,左部分为图片
		frame_right1.pack(side=TOP,expand=1,fill=tk.Y)#grid分区,右上部分为显示区域
		frame_right2.pack(side=RIGHT,expand=0)#grid分区,右下部分为按钮部分
		ttk.Label(frame_left, text='原图:').pack(anchor="nw") 
		ttk.Label(frame_right1, text='车牌位置:').grid(column=0, row=0, sticky=tk.W)
		
		from_pic_ctl = ttk.Button(frame_right2, text="来自图片", width=20, command=self.from_pic)
		from_vedio_ctl = ttk.Button(frame_right2, text="来自摄像头", width=20, command=self.from_vedio)
		#from_img_pre = ttk.Label(frame_right2,text="查看形状预处理图像",width=20,command=self.show_img_pre)
		self.image_ctl = ttk.Label(frame_left)
		self.image_ctl.pack(anchor="nw")
		
		self.roi_ctl = ttk.Label(frame_right1)
		self.roi_ctl.grid(column=0, row=1, sticky=tk.W)
		ttk.Label(frame_right1, text='识别结果:').grid(column=0, row=2, sticky=tk.W)
		self.result_ctl = ttk.Label(frame_right1, text="")
		self.result_ctl.grid(column=0, row=3, sticky=tk.W)
		self.color_ctl = ttk.Label(frame_right1, text="", width="20")
		self.color_ctl.grid(column=0, row=4, sticky=tk.W)
		from_vedio_ctl.pack(anchor="se", pady="5")
		from_pic_ctl.pack(anchor="se", pady="5")
		self.predictor = predict.Predict()
Beispiel #2
0
 def detect(self):
     if self.flag==1:   #图片识别模式
         imageout = QImage()
         imageout.load(self.pic)   #载入选择图片
         self.detectlabele.setGeometry(100, 515, 200, 150)
         self.detectlabele.setPixmap(QPixmap.fromImage(imageout))
         self.detectlabele.setScaledContents(True)
         out=predict.Predict(self.pic,self.vgg)  #识别,返回结果
         self.textlable.setText(out)
         self.textlable.setFont(QFont("Microsoft YaHei",13))  #展示识别结果
         self.textlable.setGeometry(310,570,80,30)
     if self.flag==2:    #摄像头模式
         imageout = QImage()
         imageout.load(self.image_path)   #载入摄像头传回的图片
         self.detectlabele.setGeometry(100, 515, 200, 150)
         self.detectlabele.setPixmap(QPixmap.fromImage(imageout))
         self.detectlabele.setScaledContents(True)
         out=predict.Predict(self.image_path,self.vgg)  #识别,返回结果
         self.textlable.setText(out)
         self.textlable.setFont(QFont("Microsoft YaHei", 13))  #展示识别结果
         self.textlable.setGeometry(310, 570, 80, 30)
Beispiel #3
0
    def post(self):

        args = parse_args()
      
        if args['type'] in [None, 'object']:
            p = prd.Predict()
        else:
            abort(400, msg='Invalid Model:{}'.format(args['type']))
            
        fip,ext = get_file(args)
        detections = p.predict(fip,ext, args)

        return detections
Beispiel #4
0
def Main(imgPath, cached=True):
    imgRGB = cv2.imread(imgPath)
    subImgs = roughdetect.RoughDetect(imgRGB)
    sess = tf.Session()
    pred = predict.Predict(sess, '.\\model')
    res = []
    for subImg in subImgs:
        if cached:
            cache.Cache(subImg)
        rectL = crop.Crop(subImg, crop.condition1, crop.thres1)
        subImgDeskewH = deskewH.DeskewH(subImg, rectL)
        imgRes = deskewV.DeskewV(subImgDeskewH)
        res.append(pred.predict(imgRes))
    sess.close()
    return max(res)
Beispiel #5
0
 def __init__(self, skipTest = False):
     import sys
     import os
     elevationPath = os.getcwd() + os.sep + "elevation"
     sys.path.append(elevationPath)
     elevationPath += os.sep + "elevation"
     sys.path.append(elevationPath)
     elevationPath += os.sep + "cmds"
     sys.path.append(elevationPath)
     import predict as elevation
     self.model = elevation.Predict()
     #touchFile = open("progressCounter/modelLoaded.progress", 'w')
     #touchFile.close()
     if not skipTest:
         self.testModel()
Beispiel #6
0
    def __init__(self, image_file):
        MODEL_DIR = 'imagenet_model'
        NUM_TOP_PREDICTIONS = 1
        PBTXT = 'imagenet_2012_challenge_label_map_proto.pbtxt'
        UID = 'imagenet_synset_to_human_label_map.txt'
        DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'

        predict_inst = predict.Predict(MODEL_DIR, NUM_TOP_PREDICTIONS,
                                       DATA_URL, PBTXT, UID)

        predict_inst.maybe_download_and_extract()

        predict_inst.run_inference_on_image(image_file)

        self.result = predict_inst.get_final_result()
Beispiel #7
0
    def predict(self, pace=0, soft=False):
        para_dict = {}
        exp = str(self.exp)
        if soft:
            para_dict['predict'] = os.path.join('./MAE/mae{}'.format(exp), 'MAEOnTrainPick{}.txt'.format(pace))
            para_dict['test'] = os.path.join('./images/txt{}'.format(exp), 'trainPick{}.txt'.format(pace))
            para_dict['model'] = os.path.join('./checkpoints/M{}'.format(exp), '{}VGG_iter_{}.caffemodel'.format(pace-1, self.max_step))
            para_dict['deploy'] = os.path.join('./tmp/Exp{}'.format(exp), '{}VGG-deploy.prototxt'.format(pace-1))
        if not soft:           
            para_dict['predict'] = os.path.join('./MAE/mae{}'.format(exp), '{}MAEOnTrainLeft0.txt'.format(pace-1))
            para_dict['test'] = os.path.join('./images/txt{}'.format(exp), 'trainLeft0.txt')
            para_dict['model'] = os.path.join('./checkpoints/M{}'.format(exp), '{}VGG_iter_{}.caffemodel'.format(pace-1, self.max_step))
            para_dict['deploy'] = os.path.join('./tmp/Exp{}'.format(exp), '{}VGG-deploy.prototxt'.format(pace-1))

        diff = predict.Predict(para_dict)
Beispiel #8
0
    def __init__(self, image_file):
        model_dir = 'imagenet_model'
        num_top_predictions = 1
        pbtxt = 'imagenet_2012_challenge_label_map_proto.pbtxt'
        uid = 'imagenet_synset_to_human_label_map.txt'
        DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'

        predict_inst = predict.Predict(model_dir, num_top_predictions,
                                       DATA_URL, pbtxt, uid)

        predict_inst.maybe_download_and_extract()

        predict_inst.run_inference_on_image(image_file)

        self.result = predict_inst.get_final_result()

        os.remove(image_file)
    def __init__(self):

        # load the dataset from the CSV file
        reader = csv.reader(open("normalized_car_features.csv", "r"),
                            delimiter=",")
        x = list(reader)
        features = np.array(x[2:]).astype("float")
        np.random.shuffle(features)

        # car attribute and price are splitted, note that 1 is appended at each car for the bias
        data_x = np.concatenate(
            (features[:, :3], np.ones((features.shape[0], 1))), axis=1)
        data_y = features[:, 3:]

        # we save the dataset metadata for the prediction part of the network
        self.predict = util.Predict(float(x[0][0]), float(x[0][1]),
                                    float(x[0][2]), float(x[0][3]),
                                    float(x[0][4]), float(x[0][5]))

        # we set a threshold at 80% of the data
        self.m = float(features.shape[0])
        self.m_train_set = int(self.m * 0.8)

        # we split the train and test set using the threshold
        self.x, self.x_test = data_x[:self.m_train_set, :], data_x[
            self.m_train_set:, :]
        self.y, self.y_test = data_y[:self.m_train_set, :], data_y[
            self.m_train_set:, :]

        # we init the network parameters
        self.z2, self.a2, self.z3, self.a3, self.z4, self.a4 = (None, ) * 6
        self.delta2, self.delta3, self.delta4 = (None, ) * 3
        self.djdw1, self.djdw2, self.djdw3 = (None, ) * 3
        self.gradient, self.numericalGradient = (None, ) * 2
        self.Lambda = 0.01
        self.learning_rate = 0.01

        # we init the weights using the blog post values
        self.w1 = np.matrix([[0.01, 0.05, 0.07], [0.2, 0.041, 0.11],
                             [0.04, 0.56, 0.13], [0.1, 0.1, 0.1]])

        self.w2 = np.matrix([[0.04, 0.78], [0.4, 0.45], [0.65, 0.23],
                             [0.1, 0.1]])

        self.w3 = np.matrix([[0.04], [0.41], [0.1]])
def mnist_request():
    if request.method == 'GET':
        resp = render_template('index.html')
    elif request.method == 'POST':
        with Image.open(BytesIO(request.data)) as img:
            img = img.convert('L')  # convert into grey-scale
            img = img.point(lambda i: i < 150 and 255)  # better black and white
            img = ImageOps.expand(img, border=1, fill='black')  # add padding
            rimg = _resize_algorithm(img, (28, 28))
            img.thumbnail((28, 28), rimg)  # resize back to the same size
            img = np.array(img)
            img = _process_array(img)
            img.save('./trained_model/input_image.jpg')

            pre = predict.Predict()

            resp = jsonify(pre)

    return resp
    def get_predict(self, expts, **kwargs_prior):
        def f(p):
            return np.array([self(t, p) for t in expts])

        def Df(p):
            jac = []
            for t in expts:
                jac.append([t, t**2])
            return np.array(jac)

        pred = predict.Predict(f=f,
                               Df=Df,
                               p0=self.p0,
                               pids=self.pids,
                               yids=expts.yids)

        if kwargs_prior:
            pred.set_prior(**kwargs_prior)
        return pred
import capture
import bounding_boxes
import predict
import tts
import pytesseract
import cv2
import sys

print("Enter 1 for book reading \n Enter 2 for scene images")
a = int(input())

#orig_img, gray_img = cv2.imread(sys.argv[1]), cv2.imread(sys.argv[1], 0)
orig_img, gray_img = capture.Capture()
custom_config = r'--oem 3 --psm 6'

if a == 1:
    text = pytesseract.image_to_string(orig_img, config=custom_config)

elif a == 2:
    letters, words = bounding_boxes.get_bboxes(orig_img, gray_img)
    #print(len(words))
    #text = ' '.join([pytesseract.image_to_string(word, config = custom_config) for word in words if word.shape[1] > 0 and word.shape[1] > 0])
    text = ' '.join(
        [''.join([predict.Predict(letter) for letter in _]) for _ in letters])

print(text)
tts.texttospeech(text)
Beispiel #13
0
import csv
import numpy as np
import tensorflow as tf
import predict as util

# read the data from the CSV
reader = csv.reader(open("normalized_car_features.csv", "rb"), delimiter=",")
x = list(reader)
features = np.array(x[2:]).astype("float")
np.random.shuffle(features)

predict = util.Predict(float(x[0][0]), float(x[0][1]), float(x[0][2]),
                       float(x[0][3]), float(x[0][4]), float(x[0][5]))

data_x = features[:, :3]
data_y = features[:, 3:]

# size of the dataset
m = float(features.shape[0])

# size of the train set
train_set_size = int(m * 0.8)

# the data are splitted between the train and test set
x_data, x_test = data_x[:train_set_size, :], data_x[train_set_size:, :]
y_data, y_test = data_y[:train_set_size, :], data_y[train_set_size:, :]

# regularization strength
Lambda = 0.01
learning_rate = 0.01
Beispiel #14
0
    model_state_dict = model.state_dict()
    model_source = {
        "settings": args,
        "model": model_state_dict,
        "word2idx": data['word2idx'],
        "char2idx": data['char2idx'],
        "max_len": data["max_len"],
        "predicate2id": data["predicate2id"],
    }
    torch.save(model_source, f"{os.path.join(args.model_path, 'model.pt')}")


os.makedirs("weights", exist_ok=True)

data["model"] = model
predict = predict.Predict(model_datas=data, cuda=True)
best_f1 = 0

try:
    print('-' * 90)
    for epoch in range(args.epochs):
        train(epoch)
        print('-' * 90)
        dev(epoch)
        print('-' * 90)
        predict.update_model(model)
        f1 = test(epoch, predict)
        if f1 > best_f1:
            print(f"new best f1 score {f1:.4f} and save model")
            best_f1 = f1
            model.save_model(
Beispiel #15
0
                              db='vaData')
     cursor = dbConn.cursor()
     sql = "CREATE TABLE IF NOT EXISTS " + 'cond_' + todayStr + \
           "(hour int NOT NULL AUTO_INCREMENT, cond varchar(30) NOT NULL, " \
           "PRIMARY KEY (hour))ENGINE=Innodb DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1;"
     cursor.execute(sql)
     dbConn.commit()
     dbConn.close()
     curMinute = minute
 if int(second) > int(curSecond) + 10:
     print(second)
     if hour > curHour:
         curHour = hour
     input = getLast24HoursData()
     print(input)
     pre = predict.Predict(model, input, scaler)
     output = pre.predict()
     output = [round(x) for x in output]
     print(output)
     curSecond = second
     today = date.today()
     todayStr = today.strftime("%Y%m%d")
     dbConn = pymysql.connect(host='***',
                              port=3306,
                              user='******',
                              password='******',
                              db='vaData')
     cursor = dbConn.cursor()
     sql = "INSERT INTO " + "cond_" + todayStr + "(hour, cond) VALUES (%s, %s)"
     if round(output[0]) in maps_inverse:
         res = maps_inverse[round(output[0])]
Beispiel #16
0
def display_results_mlp(image):
    predict_obj = predict.Predict(image, (8, 8))
    prediction = predict_obj.predict_mlp()
    return render_template("display_results.html",
                           pred=prediction,
                           length=len(prediction))
Beispiel #17
0
def user(request):
    now = datetime.datetime.today()
    today = str(now)[:10]
    max_date = today
    plot_exist = None
    stocks_names = ['AAPL', 'AMZN', 'NDAQ', 'SNP', 'SCCO']
    if request.method == 'POST':
        data = request.POST
        stock_name = data['stockName']
        print(stock_name)

        start_date = now - timedelta(days=5)
        end_date = now - timedelta(days=1)

        start_date = str(start_date)
        end_date = str(end_date)

        print(start_date)
        print(end_date)

        plot = check_for_file(stock_name)
        stock_vals = get_values(plot, 0)
        dates = get_values(plot, 1)
        #   print(stock_vals)

        end_date = now.date()
        end_date = str(end_date)

        updodate = predict.Predict(stock_name).up_to_date
        if updodate == 0:
            plot_exist = False
            return render(
                request, 'user/user.html', {
                    'max_date': max_date,
                    'plot_exist': plot_exist,
                    'stocks_names': stocks_names
                })
        else:
            plot_exist = True
            pred_results = read_pred_file(stock_name)
            # print(pred_results)
            decisions = get_decisions(pred_results)
            # Send it to html
            return render(
                request, 'user/user.html', {
                    'max_date': max_date,
                    'plot_exist': plot_exist,
                    'stockVal5': stock_vals[0],
                    'stockVal4': stock_vals[1],
                    'stockVal3': stock_vals[2],
                    'stockVal2': stock_vals[3],
                    'stockVal1': stock_vals[4],
                    'day5': dates[0],
                    'day4': dates[1],
                    'day3': dates[2],
                    'day2': dates[3],
                    'day1': dates[4],
                    'pred5': decisions[0],
                    'pred4': decisions[1],
                    'pred3': decisions[2],
                    'pred2': decisions[3],
                    'pred1': decisions[4],
                    'pred0': decisions[5],
                    'stocks_names': stocks_names,
                    'stock_name': stock_name
                })
    else:
        return render(
            request, 'user/user.html', {
                'max_date': max_date,
                'plot_exist': plot_exist,
                'stocks_names': stocks_names
            })
Beispiel #18
0
from bottle import route, get, post, run, template, request, error
import numpy as np

import base64
from io import BytesIO
from PIL import Image
from binascii import a2b_base64
import predict as pr
import predict_cnn as prcnn
import csv
import common

# bottle.debug(True)

# モデルのロード
pred = pr.Predict()
# pred = prcnn.Predict()


#メニュー画面
@route('/')
def menu():
    #メニュー画面表示
    return template('index', flag=False)


#画像を受け取り、学習データに変換して保存
@post('/data')
def data():
    data = request.forms.get("learn_data")
    number = request.forms.get("number")
# We have now implemented all the code necessary to train a neural network.
print('Training Neural Network... ')
lambda_ = 3.0
# Create "short hand" for the cost function to be minimized
costFunction = lambda cf: nncf.nnCostFunction(
    cf, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_)
#cost, grad = costFunction(initial_nn_params)

result = optimize.minimize(costFunction,
                           initial_nn_params,
                           method='CG',
                           jac=True,
                           options={
                               'maxiter': 50,
                               'disp': False
                           })
nn_params = result.x

arrVal = hidden_layer_size * (input_layer_size + 1)
Theta1 = nn_params[:arrVal].reshape((hidden_layer_size, input_layer_size + 1))
Theta2 = nn_params[arrVal:].reshape((num_labels, hidden_layer_size + 1))

# Visualizing Weights
dd.displayData(Theta1[:, 1:])

# Implement Predict
prediction = p.Predict(Theta1, Theta2, X)
accuracy = np.mean(prediction == y) * 100

print('Training Set Accuracy: ', accuracy)
Beispiel #20
0
annualizedFactor = 365/219

accumulation = 0
occupation = []
R = []
time = []

cost = 0
rev = 0
####### Begin the BackTest
for i in np.arange(10,148,1):
    #try:
        #date = datetime.strptime(date[i],'%Y/%m/%d')
    #except:
        #date = datetime.strptime(date[i],'%Y-%m-%d')
    prediction = predict.Predict(i-1)

    #################PART1 BUY SIDE#################
    ########## 一次买入1000股 && 当日平仓
    ###### Open Buy
    if prediction == 1:
        if flag == 0:
            buy_price = OpenPrice[i]
            print(str(date[i])+" Buy 50ETF"+" the price is "+str(buy_price))
            accumulation += buy_price*1000
            #if flag == 0:
            flag = 1
            #if cost == 0:
                #cost = buy_price * 1000 + fee
            #else:
                #cost += buy_price * 1000 + fee
Beispiel #21
0
    train.train(train_dict)

    # predict on train set to pick samples for each pace
    para_dict = {}
    para_dict['pretrain_model'] = (checkpointsPath, pace, dataset_, 100)
    para_dict['train_txt'] = train_dict['train_txt']
    para_dict['img_dir'] = train_dict['img_dir']
    para_dict['lr'] = train_dict['lr']
    para_dict['num_trees'] = train_dict['num_trees']
    para_dict['tree_depth'] = train_dict['tree_depth']
    para_dict['pace'] = pace
    para_dict['num_classes'] = train_dict['num_classes']

    # predict on pick set
    para_dict['test_txt'] = './Exp{}/images/Pick-{}.txt'.format(Exp, pace)
    para_dict['predict_txt'] = './Exp{}/Pred/PredOnPickset-{}.txt'.format(
        Exp, pace)
    predict.Predict(para_dict)

    # predict on left set
    para_dict['test_txt'] = './Exp{}/images/Left-{}.txt'.format(Exp, pace)
    para_dict['predict_txt'] = './Exp{}/Pred/PredOnLeftset-{}.txt'.format(
        Exp, pace)
    predict.Predict(para_dict)

    # predict on test set
    para_dict['test_txt'] = train_dict['test_txt']
    para_dict['predict_txt'] = './Exp{}/Pred/PredOnTestset-{}.txt'.format(
        Exp, pace)
    predict.Predict(para_dict)
            'remain': parameters['remain'],
            'trade_price': parameters['trade_price'],
            'slide': parameters['slide']
        }
        tradeamount0 = parameters['tradeamount']
        position = parameters['position']
        holdflag = parameters['holdflag']
    else:
        cf = configIO.configIO(config_file=cofile)

        # if sell order exist tradeamount should be
    autoTrading = AutoTrading(holdflag=holdflag,
                              order_places=order_places,
                              tradeamount=tradeamount0,
                              position=position)
    prediction = predict.Predict()

    hilos = technical_fx_bidirc.HILO()
    collateral = autoTrading.get_collateral()
    predict.print_and_write('Collateral: %f Profit: %f ' %
                            (collateral[0], collateral[1]))
    tradingtimes = 0
    if holdflag == False:
        curthis = 'hi'
    else:
        curthis = 'lo'

    while 1:
        this_maintance_time = 0
        if tradingtimes > 0:  # get the buy and sell price of last hour
            sell0 = sell
Beispiel #23
0
    if not os.path.isdir('./entropy/train/'):
        os.makedirs('./entropy/train/')
    fn_newEntropy = './entropy/train/' + str(pace) + 'entropy.txt'
    with open(fn_newEntropy, 'w') as f:
        f.writelines(lines)

    with open(left_txt, 'r') as f:
        left_lines = f.readlines()
    if len(left_lines) > 0:
        pred_dict = {}

        pred_dict['test'] = os.path.join('./images/txt' + str(Exp),
                                         'trainLeft' + str(pace) + '.txt')
        pred_dict['predict'] = os.path.join(
            './MAE/mae' + str(Exp), 'MAEOnTrainLeft' + str(pace) + '.txt')
        pred_dict['deploy'] = os.path.join(train_dict['tmp_dir'],
                                           str(pace) + 'VGG-deploy.prototxt')

        pred_dict['model'] = os.path.join(
            train_dict['save'],
            str(pace) + 'VGG_iter_{}.caffemodel'.format(max_step))
        diff_ave = predict.Predict(pred_dict)
        with open('./Entropy.txt', 'r') as f:
            lines = f.readlines()
        fn_save_entropy = os.path.join('./entropy/E' + str(Exp),
                                       'entropy' + str(pace) + '.txt')
        with open(fn_save_entropy, 'w') as f:
            f.writelines(lines)

        assert len(lines) > 2, 'predict entropy.txt is null!'
Beispiel #24
0
def predictrunner(queue, request):
    import predict
    pr = predict.Predict()
    pr.do_learntestlist(queue, request)
Beispiel #25
0
from flask import Flask, jsonify, request
from flask_restful import Resource, Api, reqparse, abort, Resource
import predict
import json
local_dir = "/var/www/html/bitpred/API";
p = predict.Predict(model_name = local_dir+'/model.hdf5')

# parser = reqparse.RequestParser()
# parser.add_argument("task")

app = Flask(__name__)
api = Api(app)

class PredictSentiment(Resource):
    def get(self):
        return {'info': 'This API is designed to predict the sentiment (bearish/bullish) of bitcoin data'}
    def post(self):
        args = request.get_json(force=True)
        # print(args)
        return jsonify(p.pred(query = args))

api.add_resource(PredictSentiment, '/')

if __name__ == '__main__':
    app.run(debug=True, port=5055)