def run(self):
        if self.camera is None:
            self.camera = cv2.VideoCapture(0)
            # keep looping, until interrupted
            keypress = cv2.waitKey(20) & 0xFF
            calibrate_print_flag = calibrated_print_flag = False
            letter_last = None
            (grabbed, frame) = self.camera.read()
            frame = self.format_frame(frame)
            (height, width) = frame.shape[:2]
            # get the ROI
            self.set_roi(int(floor(1 / 2 * width)), int(floor(4 / 4 * width)),
                         int(floor(0 / 3 * height)),
                         int(floor(1 / 2 * height)))

            while keypress != ord("q"):
                (grabbed, frame) = self.camera.read()
                frame = self.format_frame(frame)

                keypress = cv2.waitKey(50) & 0xFF

                frame = self.draw_roi(frame)

                cv2.imshow("Video Feed", frame)

                # pass roi to frame handler
                roi = self.get_roi(frame)
                roi = cv2.flip(roi, 1)

                self.frame_handler.add_frame(roi)

                # print letter
                if self.frame_handler.is_calibrated():
                    letter = self.frame_handler.get_letter()
                    if letter is not letter_last:
                        if letter is -1:
                            print("No letter recognized")
                        elif letter is not None:
                            print("Recognized letter: " + self.letters[letter])
                        letter_last = letter
                else:
                    if self.frame_handler.is_ready_to_calibrate():
                        if keypress == ord('c'):
                            self.frame_handler.start_calibration(roi)
                        if not calibrate_print_flag:
                            print(
                                "Put your hand in the green box and press c to calibrate..."
                            )
                            calibrate_print_flag = True
                    if self.frame_handler.is_calibrated(
                    ) and not calibrated_print_flag:
                        print("Calibrated..")
                        calibrated_print_flag = True

            # free up memory
            self.camera.release()
            self.frame_handler.stop()
            cv2.destroyAllWindows()
Esempio n. 2
0
def showDataFigure(dataArr, *args):
    m, n = shape(dataArr)
    print m, n
    example_width = round(sqrt(n))
    print "特征数目:", n
    print "example_width:", example_width  # 20
    example_height = n / example_width  # 20
    display_rows = floor(sqrt(m))  # 10
    display_cols = ceil(m / display_rows)  # 10
    pad = 1
    display_array = -ones((pad + display_rows * (example_height + pad), pad + display_cols * (example_width + pad)))
    print "display_array 的维度为:", shape(display_array)
    curr_ex = 0;
    for j in range(0, int(display_rows)):
        for i in range(0, int(display_cols)):
            # for j in range(0, int(1)):
            #for i in range(0, int(1)):
            if curr_ex >= m:
                break
            max_val = max(abs(display_array[curr_ex, :]))
            #print "##################maxval",max_val
            display_array[
            int(pad + j * (example_height + pad)): int(pad + j * (example_height + pad)) + int(example_height),
            int(pad + i * (example_width + pad)):int(pad + i * (example_width + pad)) + int(example_width)] = \
                reshape(dataArr[curr_ex, :], (example_height, example_width)) / max_val
            curr_ex = curr_ex + 1;
        if curr_ex >= m:
            break;
    plt.imshow(display_array.T, CM.gray)  # 类似matlib中的imagesc
    # scaledimage.scaledimage(display_array)
    plt.show()
Esempio n. 3
0
def split_dataset(vectors, groups, percentage_in_test_set):
    permutation = range(len(vectors))
    random.shuffle(permutation)
    vectors = [vectors[i].tolist() for i in permutation]
    groups = [groups[i].tolist() for i in permutation]
    boundary = int(floor(percentage_in_test_set * 1.0 * len(vectors)))
    return vectors[0:boundary], groups[0:boundary], vectors[boundary:], groups[
        boundary:]
Esempio n. 4
0
def loadSvdData(randomGenarate=False):
    if (randomGenarate):
        A = floor(random.rand(7, 5) * 10)  #how to genarate sparse mat
    else:
        A = [[4, 4, 0, 2, 2], [4, 0, 0, 3, 3], [4, 0, 0, 1,
                                                1], [1, 1, 1, 2, 0],
             [2, 2, 2, 0, 0], [1, 1, 1, 0, 0], [5, 5, 5, 0, 0]]
    return A
Esempio n. 5
0
    def to_rounded_int(self, special: bool = False) -> BBox:
        """Rounds BBox object to have integer coordinates.

        Keyword Arguments: special {bool} -- [Round xmin and ymin down using floor, and round xmax and ymax using
        ceil.] (default: {False})

        Returns:
            BBox -- [description]
        """
        if not special:
            return BBox(xmin=round(self.xmin),
                        ymin=round(self.ymin),
                        xmax=round(self.xmax),
                        ymax=round(self.ymax))
        else:
            return BBox(xmin=floor(self.xmin),
                        ymin=floor(self.ymin),
                        xmax=ceil(self.xmax),
                        ymax=ceil(self.ymax))
Esempio n. 6
0
    def on_bar(self, bar: BarData):
        """
        1、 计算价格相对初始位置的距离, 距离 = 格距 * 格数(总格数 当前价格为中心点)
        2、 计算当前价格到结束位的距离  price_change = 指定的最高位  - Decimal(str(bar.close_price))

        """
        self.cancel_all()  # 全撤之前的委托

        # 计算网格交易信号
        if not self.pos:
            # 以当前价格为中心轴,布一个指标大小的网,计算出启始位!
            self.grid_start = bar.close_price * (
                1 + int(self.grid_total / 2) * self.grid_distance / 100)

        self.price_change = bar.close_price - self.grid_start
        self.current_grid = self.price_change * (
            self.grid_distance / 100)  # 最大变动距离 除以 每格的变动价格(百分比) 总格数

        current_volume = self.grid_volume / bar.close_price  # 计算每份USDT可以买入多少币
        self.max_target = ceil(
            -self.current_grid) * current_volume  # 总量(最大)  = 总格数 X 每格购买量
        self.min_target = floor(
            -self.current_grid) * current_volume  # 总量(最小)  = 总格数 X 每格购买量

        self.max_target = float(
            format(self.max_target, f".{self.len_tick_decimal}f"))
        self.min_target = float(
            format(self.min_target, f".{self.len_tick_decimal}f"))

        self.write_log(f"price_change:{self.price_change}")
        self.write_log(f"current_grid:{self.current_grid}")
        self.write_log(f"max:{self.max_target}")
        self.write_log(f"min:{self.min_target}")
        self.write_log(f"current_volume:{current_volume}")

        self.pos_grid = float(format(self.pos, f".{self.len_tick_decimal}f"))

        # 做多,检查最小持仓,和当前持仓的差值
        long_volume = self.min_target - self.pos
        if long_volume > 0:
            long_price = bar.close_price + (self.price_tick * self.pay_up)

            if self.pos_grid >= 0:
                self.write_log(
                    f"买入:{self.vt_symbol},价格:{long_price},数量:{long_volume}")
                self.buy(long_price, long_volume)

        short_volume = self.max_target - self.pos
        if short_volume < 0:
            short_price = bar.close_price - (self.price_tick * self.pay_up)
            if self.pos_grid > 0:
                self.sell(short_price, abs(short_volume))
                self.write_log(
                    f"卖出:{self.vt_symbol},价格:{short_price},数量:{short_volume}")
        self.put_event()
Esempio n. 7
0
def get_shift_range(sample_rate: int, max_length: int):
    """
    :param max_length: wav file data arrays length
    :param sample_rate: wav file sampling rate
    :return: shift range based on humans hearing frequency range (20Hz - 20kHz)
    """
    minimal_shift = int(ceil(sample_rate / MAX_FREQUENCY))
    maximum_shift = int(floor(sample_rate / MIN_FREQUENCY))

    if maximum_shift > max_length:
        maximum_shift = max_length

    return minimal_shift, maximum_shift
 def _get_noise_mask(size: int) -> np.matrix:
     """Return random noise"""
     density = 0.1
     mask = np.zeros((size, size))
     for ind in np.random.choice(size - 1, int(floor(size * density))):  # pylint: disable=no-member
         how_many_elmns = random.randint(1, int(sqrt(ind)) + 1)
         for var in range(1, how_many_elmns):  # pylint: disable=unused-variable
             if random.randint(0, 1):
                 length = random.randint(1, int(sqrt(size * density)))
                 rnd_from = random.randint(1, ind) - length
                 rnd_to = rnd_from + length
                 mask[rnd_from:rnd_to, ind] = 1
                 mask[ind, rnd_from:rnd_to] = 1
     return mask
def stft_kkmw(x, M, N, R, fs):

    num_frames = (floor((len(x) - M) / R + 1))
    N_out = N / 2 + 1
    nr_mics = len(x[0])

    xt = np.zeros((M, nr_mics))
    f_vec = np.arange(N / 2 + 1) * fs / N
    t = np.arange(num_frames) * R / fs
    X = np.zeros((int(N_out), int(num_frames), int(nr_mics)),
                 dtype=np.complex_)

    win = np.transpose(np.matlib.repmat(np.hamming(M), nr_mics, 1))

    for kk in range(0, int(num_frames)):
        xt = x[kk * R:kk * R + M]
        xt = xt * win
        Xt = np.fft.fft(xt, N, 0)
        X[:, kk, 0:nr_mics] = Xt[0:int(N_out)]

    return X
Esempio n. 10
0
 def _get_quadratic_mask(size: int) -> np.matrix:
     """Return mask for triangle test matrix."""
     mask = np.zeros((size, size))
     offset = int(floor(
         size / 150))  # add extra diagonal for each 150elements grown size
     # lets add some randomly distributed diagonals
     extra_diagonals = [x for x in range(1, offset) if random.randint(0, 1)]
     for ind in range(size):
         mask[ind, ind] = 1
         mask[ind, int(ceil(ind / 2))] = 1
         mask[int(ceil(ind / 2)), ind] = 1
         mask[ind, int(ceil(ind / 4))] = 1
         mask[int(ceil(ind / 4)), ind] = 1
         # will add extra diagonals randomly
         for add in extra_diagonals:
             if ind + add < size:
                 mask[ind + add, ind] = 1
                 mask[ind + add, int(ceil(ind / 2))] = 1
                 mask[int(ceil(ind / 2)), ind + add] = 1
                 mask[ind + add, int(ceil(ind / 4))] = 1
                 mask[int(ceil(ind / 4)), ind + add] = 1
             if ind - add >= 0:
                 mask[ind - add, ind] = 1
                 mask[ind - add, int(ceil(ind / 2))] = 1
                 mask[int(ceil(ind / 2)), ind - add] = 1
                 mask[ind - add, int(ceil(ind / 4))] = 1
                 mask[int(ceil(ind / 4)), ind - add] = 1
     for splitter in range(int(np.sqrt(size))):
         matrix_splitter = ceil(float(pow(2, splitter + 1)))
         split_value = size - int(size / matrix_splitter)
         for ind in range(split_value, size):
             for add in [0] + extra_diagonals:
                 if split_value + add < size:
                     mask[ind, split_value + add] = 1
                     mask[split_value + add, ind] = 1
     return mask
Esempio n. 11
0
def split_dataset(vectors, groups, percentage_in_test_set):
    boundary = floor(percentage_in_test_set * 1.0 * len(vectors))
    return vectors[0:boundary], groups[0:boundary], vectors[boundary:], groups[
        boundary:]
import numpy as np
from numpy.linalg import norm
from numpy.ma import floor

from datagen.FileProviderAsl import FileProviderAsl
from preprocessing.segmentation.ColourHistogram import ColourHistogram

paths_dict = FileProviderAsl(sets=["E"], alphabet=["a"]).img_file_paths
winsize = 3
samples = []
for paths in paths_dict.values():
    for path in paths:
        img = read_image(path)
        img_filtered = cv2.pyrMeanShiftFiltering(img, 5, 50)

        y = int(floor(img.shape[0] / 2) - floor(winsize / 2))
        x = int(floor(img.shape[1] / 2) - floor(winsize / 2))
        # sample = img.copy()
        # cv2.rectangle(sample, (x, y), (x+winsize, y+winsize), (0, 255, 0))
        # cv2.imshow("Box", sample)

        window = img[y:y + winsize, x:x + winsize]
        samples.append(window.reshape(-1, 3))

n_bins = 32
bin_range = 255 / n_bins
hist = np.zeros(shape=(1, 3 * n_bins))
for sample in samples:
    hist += ColourHistogram.colour_hist(sample)

hist = hist.reshape(1, -1)
Esempio n. 13
0
def get_number_partitions(string: str, chunk_size: int) -> int:
    return floor(len(string) / chunk_size) + 1