Esempio n. 1
0
def test_funcs(img1, img2):
    img3 = img2

    funcs.show(img1)
    funcs.save(img1, filename='out_1.png')

    #funcs.getWidth funcs.getHeight
    print funcs.getWidth(img1), funcs.getHeight(img1)

    #funcs.mix
    mixed_pics = funcs.mix(img1, img3, .5)
    funcs.show(mixed_pics)

    #funcs.tint
    tinted_pic = funcs.tint(img1, (0, 0, 255), .5)
    funcs.show(tinted_pic)

    #funcs.grayscale
    gray_pic = funcs.grayscale(img1)
    funcs.show(gray_pic)
    gray_pic_2 = funcs.grayscale(img1, two_dimensional=True)
    funcs.show(gray_pic_2)

    #funcs.rotate
    img_rotate = funcs.rotate(img1, 180)
    funcs.show(img_rotate)
def write_temperatures(temperatures):
    date = datetime.datetime.now().strftime('%Y%m%d')

    try:
        df = load('history/' + date + '.df')
        df.loc[df.index.max() + 1] = temperatures
    except FileNotFoundError:
        df = pd.DataFrame(temperatures, index=[0])

    save(df, 'history/' + date + '.df')
Esempio n. 3
0
def getSeam(img, blur=1, debug=False, attractor=np.zeroes(img.shape)):

    img_original = img.copy()
    img = img.copy()
    img = funcs.grayscale(img, True)
    img = np.float32(cv2.GaussianBlur(img, (blur, blur), 0))
    derivative_kernel = np.float32([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    Ix = cv2.filter2D(img, -1, derivative_kernel)
    Iy = cv2.filter2D(img, -1, derivative_kernel.T)
    path = Ix**2 + Iy**2
    path = path**.5

    path += (atrractor * 100.0)

    if debug:
        pic_1_c_0 = path.copy()
        funcs.save(pic_1_c_0, "output/pic_1_a.png")

    kernel = np.float32([[1, 1, 1]])
    h, w = img.shape[:2]
    for i in range(1, h):
        row = path[i - 1, :]
        row = cv2.erode(row, kernel.T)
        path[i:i + 1, :] += row.T
    if debug:
        pic_1_c_1 = path.copy()
        funcs.save(pic_1_c_1, "output/pic_1_b.png")
    x = np.argmin(path[-1])
    y = h - 1
    seam = []
    seam.append(x)
    while y > 0:
        y -= 1
        minX = seam[0] - 1
        maxX = seam[0] + 2
        x = np.argmin(path[y, max(minX, 0):min(maxX, w - 1)]) + x
        if x != 0:
            x -= 1
        seam.insert(0, x)
    if debug:
        funcs.save(showSeam(pic_1_c_0, seam), "output/pic_1_c_1.png")
        funcs.save(showSeam(pic_1_c_1, seam), "output/pic_1_c_2.png")
        funcs.save(showSeam(img_original, seam), "output/pic_1_c_0.png")
    return seam
Esempio n. 4
0
         if (r[i].loaded and not r[i].excluded):
             r[i].make_groups(params, window)
             msg = 'Status: %s: %d groups generated' % (r[i].title,
                                                        len(r[i].glist))
             print(msg)
             stext.Update(value=msg)
     if (r[index].detected):
         current_img = funcs.draw_circles(r[index].data, r[index].holes,
                                          params)
         if (r[index].grouped):
             current_img = funcs.draw_groups(current_img, r[index].glist,
                                             r[index].gcrd, r[index].holes,
                                             params)
     funcs.draw_image(graph, current_img, params)
 elif event == 'Save' and opened:
     funcs.save(r, nv, fname_out, params)
     stext.Update(value='Status: Wrote centers in %s' % fname_out)
     saved = True
 elif event == '-GRAPH-' and mode == 't' and opened and r[index].loaded:
     if mouse_x0 < 0 and mouse_y0 < 0:
         mouse_x0, mouse_y0 = values['-GRAPH-']
     else:
         mouse_x1, mouse_y1 = values['-GRAPH-']
         dx = mouse_x1 - mouse_x0
         dy = mouse_y1 - mouse_y0
         params.translate(dx, dy)
         funcs.draw_image(graph, current_img, params)
         mouse_x0 = mouse_x1
         mouse_y0 = mouse_y1
 elif event == '-GRAPH-' and mode == 'z' and opened and r[index].loaded:
     if mouse_x0 < 0 and mouse_y0 < 0:
Esempio n. 5
0
            img = funcs.trans_img(trans_img)
            seam_map = funcs.trans_img(trans_map)

    return img, seam_map


#Read Image
img1 = cv2.imread("image1.png")

#pic_1_a,pic_1_b,pic_1_c_0,pic_1_c_1,pic_1_c_2
seam1 = getSeam(img1, 1, debug=True)

#pic_1_d
pic_1_d = removeSeam(img1, seam1)
funcs.save(pic_1_d, "output/pic_1_d.png")

#pic_1_e
pic_1_e, _ = carveSeams(img1, 120)
funcs.save(pic_1_e, "output/pic_1_e.png")

#pic_2_a
trans_img = funcs.trans_img(img1)
pic_2_a = showSeam(trans_img, getSeam(trans_img))
pic_2_a = funcs.trans_img(pic_2_a)
funcs.save(pic_2_a, "output/pic_2_a.png")

#pic_2_b
pic_2_b, _ = carveHorizSeams(img1, 120)
funcs.save(pic_2_b, "output/pic_2_b.png")
Esempio n. 6
0
def run_model(init, output, saver, IS_RESTORE_BASED, company_str, company,
              epochs, seq_input, seq_output, keep_prob, dropout, optimizer,
              cost, batch_size, prediction_length, sequence_length,
              processing_device, display_steps, weights, biases, total_error,
              unexplained_error, R_squared, R, MAPE, RMSE):
    merged = tf.summary.merge_all()
    with tf.device(processing_device):
        with tf.Session() as sess:
            if IS_RESTORE_BASED:
                saver.restore(
                    sess, "../modeldata/" + company_str + "/logs/model.ckpt")

            sess.run(init)
            train_writer = tf.summary.FileWriter(
                '../modeldata/' + company_str + '/logs/', sess.graph)

            train_start = time.time()
            step = 1
            while company.train.epochs_completed <= epochs:
                step += 1
                company_data, company_labels = company.train.next_batch()
                output_data = np.reshape(company_labels.T[1].T,
                                         (batch_size, prediction_length))

                _, loss, rsq, r, te, une, mape, rmse = sess.run(
                    [
                        optimizer, cost, R_squared, R, total_error,
                        unexplained_error, MAPE, RMSE
                    ],
                    feed_dict={
                        seq_input: company_data.T[1].T,
                        seq_output: output_data,
                        keep_prob: dropout
                    })

                if step % display_steps == 0:
                    print "Epochs completed: {}".format(company.train.epochs_completed) +\
                         "  loss: {}".format(loss) + "  step: {}".format(step)

                if company.train.epochs_completed == epochs - 1:
                    p_valfile = open(
                        "../graphdata/" + company_str + "_pval.js", "w")
                    p_valfile.write("var " + company_str + "_total_error = " +
                                    str(te) + ";")
                    p_valfile.write("var " + company_str +
                                    "_unexplained_error = " + str(une) + ";")
                    p_valfile.write("var " + company_str + "_R_squared = " +
                                    str(rsq) + ";")
                    p_valfile.write("var " + company_str + "_R = " + str(r) +
                                    ";")
                    p_valfile.write("var " + company_str + "_MAPE = " +
                                    str(mape) + ";")
                    p_valfile.write("var " + company_str + "_RMSE = " +
                                    str(rmse) + ";")
                    p_valfile.close()

            print "Optimization Completed. Training time:  {}sec".format(
                time.time() - train_start)
            # save weights, biases, model:
            save(sess.run(weights['layer1']),
                 "../modeldata/" + company_str + "/weights/layer1")
            save(sess.run(weights['layer2']),
                 "../modeldata/" + company_str + "/weights/layer2")
            save(sess.run(biases['layer1']),
                 "../modeldata/" + company_str + "/biases/layer1")
            save(sess.run(biases['layer2']),
                 "../modeldata/" + company_str + "/biases/layer2")
            save_path = saver.save(
                sess, "../modeldata/" + company_str + "/logs/model.ckpt")

            test_data, test_labels = company.test.next_batch()
            test_labels = np.reshape(test_labels.T[1].T[:15],
                                     (15, prediction_length))
            test_data = np.reshape(test_data.T[1].T[:15],
                                   (15, sequence_length))

            predictions = sess.run(output,
                                   feed_dict={
                                       seq_input: test_data,
                                       keep_prob: 1.0
                                   })

            predictions = np.reshape(predictions, (15, prediction_length))

        labels, pred = [], []
        for data, label, prediction in zip(test_data, test_labels,
                                           predictions):
            labels.append(np.concatenate((data, label), 0).tolist())
            pred.append(np.concatenate((data, prediction), 0).tolist())

        final_data, final_label = [], []
        temp = 1
        for d, l in zip(labels, pred):
            final_data.append(d[0])
            final_label.append(l[0])
            final_data[:-1] += pred[temp - 1:][0]
            final_label[:-1] += labels[temp - 1:][0]
            temp += 1
            # print temp

        error = 0.05
        resultfile = open("../resultfile.txt", "a")
        if pred[0][len(pred[0]) - 2] > (pred[0][len(pred[0]) - 1] + error):
            res_str = "CLOSING PRICE WILL GO UP FOR " + company_str + " >> BUY MORE SHARE..."
        else:
            res_str = "CLOSING PRICE WILL GO Down FOR " + company_str + " >> SELL MORE SHARE..."

        resultfile.write(res_str)
        resultfile.write("\n")

        plt2.plot(test_labels.T[0][:-1], color='red', label='prediction')
        plt2.plot(predictions.T[0][1:], color='blue', label='actual')
        plt2.title(company_str)
        plt2.xlabel('days')
        plt2.ylabel('normalized closing prices')
        plt2.legend(loc='upper left')
        plt2.savefig("../graph/prediction" + company_str + ".png")
        plt2.close()

        datafile = open("../graphdata/" + company_str + "_data.js", "w")
        labelfile = open("../graphdata/" + company_str + "_label.js", "w")
        datafile.write("var " + company_str + "_CLOSING_PRICE_DATA = [ 0")
        labelfile.write("var " + company_str + "_CLOSING_PRICE_LABEL = [ 0")
        for dat, lab in zip(final_data[:-1], final_label[:-1]):
            datafile.write(", '")
            labelfile.write(", '")
            datafile.write(str(dat))
            labelfile.write(str(lab))
            datafile.write("'")
            labelfile.write("'")

        datafile.write(" ];")
        labelfile.write(" ];")

        datafile.close()
        labelfile.close()
        print "Completed....."
Esempio n. 7
0
                    names.append(name)
     # found names to console
    if len(names) > 0:
        dayFlights = sort(flights[flights['localFlightDateStr']==localFlightDateStr],order=['points'])[::-1]
        sortedNames = dayFlights[:]['name']
        lastnames = ''
        for name in sortedNames:
            lastnames += '{} '.format(name.split(' ')[1])
        print (lastnames)
    else:
        print('')

    if not inPresent and mod(iSinceSave+1,nSaveInterval) == 0:
        # '''save flights ; if unpublished, publish them.'''
        publish(iflight, flights, notes, password, senderEmail, receiverEmail, adminEmail, inPresent, emailBlock)
        save(flightsFile,iflight,flights)
        writeFile('lastDateSearched.txt', loopDateStr)
        iSinceSave = 0
        print('Saved')
    '''If loopDate is localToday, wait until tomorrow'''
    while date.today() == loopDate:  # wait until next morning.  This ends for Australia at its midnight.  It ends for USA at UTC's midnight.
        inPresent = True
        loopDate -= timedelta(days=1)  # Come back to this date on sleep exit...incremented just after sleep.
        publish(iflight, flights, notes, password, senderEmail, receiverEmail, adminEmail, inPresent, emailBlock,\
                rankFlights, localAirports, groupName, googleGroupName, localeName, htmlFilePath)
        save(flightsFile,iflight,flights)
        yesterday = date.isoformat(date.today() - timedelta(days=1))
        writeFile('lastDateSearched.txt', yesterday)
        shutil.copy(flightsFile, '/media/sf_landscapes-zip/')
        iSinceSave = 0
        print('Saved')
Esempio n. 8
0

"""Candle"""

candle_names = glob.glob("candle_in\*.png")
candle_names = sorted(candle_names)
candle_imgs = []
for img in candle_names:
    candle_imgs.append(cv2.imread(img))

out1, out2, start, end = start_end_frame(candle_imgs)

candle_out = candle_imgs[start:end]

save_imgs(candle_out, "candle_out\\")
funcs.save(out1, "candle_out\out1.png")
funcs.save(out2, "candle_out\out2.png")
"""Personal"""

printer_names = glob.glob("printer_in\*.png")
printer_names = sorted(printer_names)
printer_imgs = []
for img in printer_names:
    printer_imgs.append(cv2.imread(img))

out3, out4, startp, endp = start_end_frame(printer_imgs)

printer_out = printer_imgs[startp:endp]

save_imgs(printer_out, "printer_out\\")
funcs.save(out3, "printer_out\out3.png")