Ejemplo n.º 1
0
 def __init__(
         self,
         size,
         path,
         triggered=False,
         saving=False,
         channel_folders=None,
         filename_format="recording_{0}.wav",
         min_size=None,
         sampling_rate=44100,
         parent=None
     ):
     """
     Parameters
     ----------
     size : int
         Size of each file to be saved in samples
     """
     super(SoundSaver, self).__init__(parent)
     self._buffer = RingBuffer()
     self._save_buffer = RingBuffer()
     self._idx = 0
     self.path = path
     self.saving = saving
     self.channel_folders = channel_folders
     self.triggered = triggered
     self.min_size = min_size
     self.sampling_rate = sampling_rate
     self.filename_format = filename_format
     self._file_idx = collections.defaultdict(int)
     self.size = size
     self._recording = False
     self._trigger_timer = None
Ejemplo n.º 2
0
 def __init__(self, dim, stepper, kernel, obs_var, history_len=100):
     self.dim = dim
     self.stepper = stepper
     self.k = kernel
     self.history_x = RingBuffer([dim], history_len)
     self.history_y = RingBuffer([1], history_len)
     self.obs_var_p = obs_var
     self.eps = 0.00
Ejemplo n.º 3
0
 def set_triggered(self, triggered):
     self.triggered = triggered
     self._buffer.clear()
     if self.triggered:
         self._buffer = RingBuffer(
             maxlen=int(Settings.DETECTION_BUFFER * self.sampling_rate)
         )
     else:
         self._buffer = RingBuffer()
Ejemplo n.º 4
0
 def test_two_similar_ringbuffers_are_equal(self):
     r = RingBuffer(10)
     s = RingBuffer(10)
     for i in range(20):
         r.append(i)
         s.append(i)
     self.assertEqual(
         r, s, "Fails to say that two identically filled "
         "RingBuffers are equal.")
Ejemplo n.º 5
0
 def define_constants(self):
     self.map_side_length = 2.55
     # FIMXE: hard coded goals
     # self.GOALS = [(40+2,6), (40, 6+2), (40,21), (35, 19), (30,22),  (29,10), (27,5), (20,8), (20,33), (20, 48), (5,55)]
     self.GOALS = None
     self.worldNorthTheta = None
     self.maxVelocity = 2.0
     self.history_length = 5
     self.theta_history = RingBuffer(self.history_length)
     self.e_theta_h = RingBuffer(self.history_length)
     self.blurred_paths = None
     self.path_skip = 8
Ejemplo n.º 6
0
class Stream(threading.Thread):
    """class to store the stream in a fifo (as daemon)"""
    queue = RingBuffer()

    def __init__(self, fifo):
        threading.Thread.__init__(self)
        self.fifo = fifo

    def run(self):
        """write all segments from queue to fifo"""
        try:
            # todo better directory
            with open('/tmp/loading.mov', 'r') as fd:
                loading = fd.read()
        except:
            loading = ''

        while self.queue.is_empty():
            time.sleep(1)
        try:
            os.mkfifo(self.fifo)
        except:
            pass

        with open(self.fifo, 'a+') as fifo:
            while True:
                if self.queue.is_empty():
                    segment = loading
                else:
                    segment = self.queue.pop()
                fifo.write(segment)
Ejemplo n.º 7
0
 def test_negative_index_on_partly_filled_buffer(self):
     r = RingBuffer(10)
     for i in range(5):
         r.append(i)
     self.assertEqual(
         r[-1], 4, "Fails to return the most recent datum when "
         "asked for index -1.")
Ejemplo n.º 8
0
 def test_wraps(self):
     r = RingBuffer(10)
     for i in range(20):
         r.append(i)
     self.assertEqual(
         r, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
         "Fails to wrap buffer when more data is added "
         "than the max buffer length.")
Ejemplo n.º 9
0
    def test_write_once(self):
        """signle write should return number of elements written to buffer"""

        buffer = RingBuffer(5)
        items_written = buffer.write([1, 2, 3])
        self.assertEqual(items_written,
                         3,
                         msg="3 items should have been written")
Ejemplo n.º 10
0
 def test_string_shows_buffer_and_length(self):
     r = RingBuffer(10)
     for i in range(20):
         r.append(i)
     self.assertEqual(
         str(r), "<RingBuffer of length 10 and "
         "[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]>",
         "Fails to print RingBuffer to spec.")
Ejemplo n.º 11
0
def test_ringbuffer_cannot_append_when_full():
    """pushing to a full RingBuffer fails"""
    rblength = 16
    rb = RingBuffer(rblength)
    for i in range(rblength):
        rb.append(i)

    with pytest.raises(IndexError):
        rb.append(42)
Ejemplo n.º 12
0
    def test_write_with_overflow(self):
        """
        if we want to write more items than free space in Buffer, we get only
        subset of items written in buffer
        """

        buffer = RingBuffer(5)
        num_items = buffer.write([1, 2, 3])
        self.assertEqual(num_items, 3)
        num_items = buffer.write([4, 5, 6, 7])
        self.assertEqual(num_items, 2)
Ejemplo n.º 13
0
    def __init__(self, pin):
        self.check_ticks_ms = 0
        self.ds = DS18X20(OneWire(Pin(pin)))
        self.rom = None
        self.buffer = RingBuffer(6)
        self.state = DS_IDEL

        roms = self.ds.scan()
        if roms:
            self.rom = roms[0]
            UI.LogOut(str(self.rom))
Ejemplo n.º 14
0
	def __init__(self, host, port, tamanhoJanela):
		self.host = host
		self.port = port
		self.tamanhoJanela = tamanhoJanela
		self.ultimoEnviado = -1
		self.ultimoRecebido = -1
		self.reenviados = 0
		self.buffer = RingBuffer(self.tamanhoJanela)
		self.socketCliente = iniciaSocketCliente()
		self.condition = Condition()
		self.enviando = True
Ejemplo n.º 15
0
def test_ringbuffer_clear_empties_buffer():
    """clearing a RingBuffer leaves it empty: len(rb)==0"""
    rblength = 16
    rb = RingBuffer(rblength)
    # fill buffer with random number of elements, but at least 1
    n = random.randint(1,rblength)
    for i in range(n):
        rb.append(n)

    rb.clear()

    assert len(rb) == 0
Ejemplo n.º 16
0
def test_ringbuffer_popleft_decreases_length():
    """popping from a RingBuffer reduces its length by 1"""
    rblength = 16
    rb = RingBuffer(rblength)
    # fill buffer with random number of elements, but at least 1
    n = random.randint(1,rblength)
    for i in range(n):
        rb.append(n)

    rb.popleft()

    assert len(rb) == n-1
Ejemplo n.º 17
0
def test_ringbuffer_append_increases_length():
    """pushing to a RingBuffer increases its length by 1"""
    rblength = 16
    rb = RingBuffer(rblength)
    # fill buffer with random number of elements, but at most length-1
    n = random.randint(1,rblength-1)
    for i in range(n):
        rb.append(n)

    rb.append(42)

    assert len(rb) == n+1
Ejemplo n.º 18
0
    def run(self):

        self.A0 = RingBuffer(
            self.records
        )  # creates a buffer with maximum numbers equal to the number of records /reading
        self.A1 = RingBuffer(self.records)
        self.A2 = RingBuffer(self.records)
        self.A3 = RingBuffer(self.records)

        if self.sleep > 0.01 * 4:
            self.sleep = self.sleep - 0.01 * 4  # each reading of the ADC takes about 0.01s. this time is compensated during sleep

        while True:
            # Adds measures and keep track of num of measurements
            self.A0.append(adc.read_adc(
                0, gain=GAIN, data_rate=DATA_RATE))  # pin gain and data_rate
            self.A1.append(adc.read_adc(
                1, gain=GAIN, data_rate=DATA_RATE))  # pin gain and data_rate
            self.A2.append(adc.read_adc(
                2, gain=GAIN, data_rate=DATA_RATE))  # pin gain and data_rate
            self.A3.append(adc.read_adc(
                3, gain=GAIN, data_rate=DATA_RATE))  # pin gain and data_rate

            time.sleep(self.sleep)
Ejemplo n.º 19
0
	def __init__(self,sample_rate=16000,channels=1,audio_length=80):
		Thread.__init__(self)
		
		self.p = pyaudio.PyAudio()

		self.running = False
		self.input_device = 'default'
		self.bytes_per_sample=2
		self.sample_rate = sample_rate
		self.channels = channels
		self.audio_length = audio_length
		self.blocksize = int(((self.sample_rate) * (self.audio_length) / 1000) * self.channels * self.bytes_per_sample)


		self.audio_buffer = RingBuffer()
Ejemplo n.º 20
0
    def test_a_typical_workflow(self):
        """here we test typical buffer workflow (writes and reads)"""

        buffer = RingBuffer(5)
        buffer.write([1, 2, 3])
        buffer.write([4, 5, 6])
        buffer.read()
        buffer.read()
        buffer.write([7, 77, 777, 7777])
        buffer.read()
        buffer.read()
        buffer.read()
        buffer.read()
        buffer.read()

        with self.assertRaises(BaseException):
            item = buffer.read()
Ejemplo n.º 21
0
    def __init__(self):
        ChatBox.__init__(self, [
            "msg_public", "msg_team", "msg_private", "msg_squad", "msg_clan",
            "msg_server", "_HCBinternal"
        ])
        self.buffer.setFadeTop(True)

        #history messages
        self.historyBuffer = MessageBuffer([
            "msg_public", "msg_team", "msg_private", "msg_squad", "msg_clan",
            "msg_server", "_HCBinternal"
        ])
        self.historyBuffer.setEditable(False)
        scroll = glass.GlassScrollArea(self.historyBuffer)
        scroll.setScrollPolicy(glass.GlassScrollArea.SHOW_NEVER,
                               glass.GlassScrollArea.SHOW_ALWAYS)
        scroll.setAutoscroll(True)
        self.add(scroll)
        self.historyBuffer.parentScroll = scroll
        scroll.setVisible(False)
        for i in range(40):
            self.historyBuffer.addRow(" ")

        self.scroll.setVerticalScrollPolicy(glass.GlassScrollArea.SHOW_NEVER)

        self.input.setVisible(False)

        self.inputType = glass.GlassLabel("(squad)")
        self.inputType.setAlignment(glass.Graphics.RIGHT)
        self.add(self.inputType)

        self.history = RingBuffer(16)
        self.historyIndex = 0
        self.chatType = "all"
        self.replyTarget = ""
        self.oldHeight = 0
        self.typing = False

        self.fade = ActionSequence(savage.WaitAction(5000),
                                   savage.CheckAction(self.typing, False),
                                   FadeOutAction(self))
        self.showHistory(False)
Ejemplo n.º 22
0
	def __init__( self ):
		ChatBox.__init__(self, ["msg_public", "msg_team", "msg_private", "msg_squad", "msg_clan", "_HCBinternal"]);
		self.buffer.showTime(1);
		self.buffer.setFadeTop(1);
		
		self.scroll.setVerticalScrollPolicy( glass.GlassScrollArea.SHOW_NEVER );
		
		self.input.setVisible(False);
		
		self.inputType = glass.GlassLabel("(squad)");
		self.inputType.setAlignment( glass.Graphics.RIGHT );
		self.add(self.inputType)
		
		self.history = RingBuffer(16);
		self.historyIndex = 0;
		self.chatType = "all";
		self.replyTarget = "";
		self.oldHeight = 0;
		
		self._historyShown = 0;
		self.showHistory(0);
Ejemplo n.º 23
0
    def __init__(self,
                 sampling_period,
                 minimum_pip=MINIMUM_PIP,
                 window_length=5,
                 polynomial_order=3,
                 buffer_length=10):
        """
        Parameters
        ----------
        sampling_period : float
            The amount of time between data samples.
        minimum_pip=tetra_constants.MINIMUM_PIP : float
            The maximum pressure considered to be PIP.
        window_length=5 : int
            The number of points sampled for a low-pass filter of the
            data.  It must be odd.
        polynomial_order=3 : int
            The order of the Savitsky-Golay filter used to smooth the
            data.  It must be less than window_length.
        buffer_length=10 : int
            The number of data points considered when smoothing.
        """
        if (window_length > buffer_length):
            raise ValueError("window_length must be <= buffer_length")
        if (window_length % 2 != 1):
            raise ValueError("window_length must be odd")
        if (buffer_length <= window_length):
            raise ValueError("buffer_length must be greater in length "
                             "than window_length")

        self._sampling_period = sampling_period
        self._minimum_pip = minimum_pip
        self._currently_in_pip_range = False
        self._current_pip = minimum_pip
        self._window_length = window_length
        self._polynomial_order = polynomial_order
        self._buffer_length = buffer_length
        self._data_buffer = RingBuffer(buffer_length,
                                       initial_state=[minimum_pip] *
                                       buffer_length)
Ejemplo n.º 24
0
	def __init__(self,sample_rate=16000,channels=1,audio_length=80):
		Thread.__init__(self)

		self.running = False
		self.input_device = 'default'
		self.bytes_per_sample=2
		self.sample_rate = sample_rate
		self.channels = channels
		self.audio_length = audio_length
		self.blocksize = int(((self.sample_rate) * (self.audio_length) / 1000) * self.channels * self.bytes_per_sample)

		self._cmd = [
			'arecord',
			'-q',
			'-t', 'raw',
			'-D', self.input_device,
			'-c', str(self.channels),
			'-f', 's16',
			'-r', str(self.sample_rate),
		]

		self._arecord = None
		self.audio_buffer = RingBuffer()
Ejemplo n.º 25
0
def updatefiles():
    global lastupdate

    try:
        jobs = ss.worksheet("_Jobs")
        jobsmap = ss.worksheet("_JobMap")
    except gspread.WorksheetNotFound:
        jobs = ss.add_worksheet("_Jobs", 101, 4)
        jobs.append_row(
            ["Created", "Updated", "Completed", "Progress", "FP", "Name"])
        jobsmap = ss.add_worksheet("_JobMap", MAX_JOBS + 1, 5)
        jobsmap.append_row(
            ["SheetID", "JobName", "Completed", "Started", "Last Updated"])
        for i in range(MAX_JOBS):
            jobsmap.append_row([
                "Sheet%d" % (i + 1), ".", "No", "0",
                "=INDIRECT(A2&\"!A2\", TRUE)"
            ])

    files = [f for f in os.listdir(LOGS_DIR) if f.endswith(LOGS_EXTENSION)]

    for f in files:
        currtime = time.time()
        epochtime = currtime / (60 * 60 * 24) + 25569
        name = f[:-len(LOGS_EXTENSION)]
        if name == ".":
            print("Invalid job name '.'")
            continue
        f = os.path.join(LOGS_DIR, f)
        last_modified = os.stat(f).st_mtime
        if last_modified < lastupdate:
            continue

        print("Updating %s" % name)
        # Find sheet for job
        currjobs = jobsmap.col_values(2)
        try:
            idx = currjobs.index(name)
            jobsheet = ss.worksheet(idx2sheet(idx))
            jobsmap.update_cell(idx + 1, 3, 'No')
        except ValueError:
            try:
                idx = currjobs.index('.')
            except ValueError:
                currcompletion = jobsmap.col_values(3)
                try:
                    idx = currcompletion.index('Yes')
                except ValueError:
                    continue
            jobsmap.update_cells([
                Cell(idx + 1, 2, name),
                Cell(idx + 1, 3, 'No'),
                Cell(idx + 1, 4, epochtime)
            ])
            currjobs[idx] = name
            sheetid = idx2sheet(idx)
            try:
                jobsheet = ss.worksheet(sheetid)
                jobsheet.clear()
            except gspread.WorksheetNotFound:
                jobsheet = ss.add_worksheet(sheetid, 50, 5)
            jobsheet.append_row(
                ['Timestamp', 'Line', 'Progress', 'Status', 'Task'])
            jobs.append_row([epochtime, epochtime, '', 0, 0, name])

        # Update job info
        rowidx = jobs.find(name).row
        row = jobs.row_values(rowidx)
        completed = False
        fp = int(row[FP_COL - 1])
        fd = open(f, "r")
        fd.seek(0, 2)
        filelen = fd.tell()
        # TODO: Check previous N characters match previous line
        if filelen < fp:
            # This job got restarted; update status
            jobsmap.update_cells([
                Cell(idx + 1, 2, name),
                Cell(idx + 1, 3, 'No'),
                Cell(idx + 1, 4, epochtime)
            ])
            jobsheet.clear()
            jobsheet.append_row([
                'Timestamp', 'Line', 'Progress', 'Status', 'Task', "Rate",
                "Median Rate", "Rate Ratio", "Smoothed Rate", "ETA"
            ])
            jobs.update_cells([
                Cell(rowidx, 1, epochtime),
                Cell(rowidx, UPDATED_COL, epochtime),
                Cell(rowidx, COMPLETED_COL, ''),
                Cell(rowidx, PROGRESS_COL, 0),
                Cell(rowidx, FP_COL, 0)
            ])
            fp = 0
            percentage = 0
        else:
            percentage = float(row[PROGRESS_COL - 1])

        fd.seek(fp)
        linesbuffer = RingBuffer(MAX_LINES)

        status = ""
        task = ""
        for line in fd.readlines():
            if line.strip():
                if line.startswith("status:") or line.startswith("Status:"):
                    status = line[len("status:"):].strip()
                if line.startswith("task:") or line.startswith("Task:"):
                    task = line[len("task:"):].strip()
                line_progress = findprogress(line)
                if line_progress > 0:
                    percentage = line_progress
                line = [
                    epochtime, line[:-1], percentage,
                    status if status else "=D3", task if task else "=E3"
                ]
                line.append(
                    "=if(ISBLANK(C3),0,if(OR(A2=A3,C2=C3),F3,(A2-A3)/(C2-C3)))"
                )  # Rate
                line.append("=MEDIAN(F2:F11)")  # Median Rate
                line.append("=if(F2=0,0,G2/F2)")  # Rate Ratio
                cond = "H2:H11,\">0.95\",H2:H11, \"<1.05\""
                line.append("=if(COUNTIFS(%s)=0,H2,AVERAGEIFS(F2:F11,%s))" %
                            (cond, cond))  # Smoothed Rate
                line.append("=if(I2=0,\"inf\",A2+(100-C2)*I2)")  # ETA
                linesbuffer.push(line)

        for line in linesbuffer:
            jobsheet.insert_row(line, 2, value_input_option='USER_ENTERED')

        if status.startswith("Error") or status.startswith("error"):
            jobsmap.update_cell(currjobs.index(name) + 1, 3, 'Error')

        if percentage == 100:
            completed = True
            # FIXME: Other completion criteria
            jobsmap.update_cell(currjobs.index(name) + 1, 3, 'Yes')

        fp = fd.tell()
        updated_cells = [
            Cell(rowidx, UPDATED_COL, epochtime),
            Cell(rowidx, PROGRESS_COL, percentage),
            Cell(rowidx, FP_COL, fp)
        ]
        if completed:
            updated_cells.append(Cell(rowidx, COMPLETED_COL, epochtime))
        jobs.update_cells(updated_cells)
    lastupdate = currtime
Ejemplo n.º 26
0
def main():
    """
    image processing occurs here
    """

    intrusion_detected = False
    alarm_hold_time = time.time() + 5

    frame_rate = 60
    refresh_time = int((1 / frame_rate) * 1000)

    ###########################################################################
    # VIDEO CAPTURE: open camera. user -1 for default. 1 for c920 or external
    # camera.
    ###########################################################################
    #vc = cv2.VideoCapture(-1)
    #vc = cv2.VideoCapture("Video 3.wmv")
    vc = cv2.VideoCapture(0)

    ###########################################################################
    # create processing windows
    ###########################################################################

    cv2.namedWindow("src", flags=cv2.WINDOW_NORMAL)
    cv2.namedWindow("gray", flags=cv2.WINDOW_NORMAL)
    cv2.namedWindow("Vish Movement Detector", flags=cv2.WINDOW_NORMAL)
    cv2.namedWindow("image_delta_open", flags=cv2.WINDOW_NORMAL)
    cv2.namedWindow("noise removal", flags=cv2.WINDOW_NORMAL)

    ###########################################################################
    # create window with trackbars for runtime adjusting
    ###########################################################################
    create_trackbars()

    ###########################################################################
    # flush camera buffer. Don't quite understand why
    ###########################################################################
    for i in range(10):
        cv2.waitKey(refresh_time)
        _, src = vc.read()

    ###########################################################################
    # create a ring buffer to handle background history
    ###########################################################################
    prev_history_length = get_trackbar_pos("HistoryLength")
    rb = RingBuffer(prev_history_length)

    ###########################################################################
    # process image
    ###########################################################################
    print("start processing image")
    while True:

        # Clear
        os.system('cls' if os.name == 'nt' else 'clear')

        #######################################################################
        # start measuring time
        #######################################################################
        start_time = time.time()

        #######################################################################
        # read data directly from the camera or video
        #######################################################################
        _, src = vc.read()

        #######################################################################
        # convert to hsv and gray frames
        #######################################################################
        gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
        cv2.imshow("gray", gray)

        #######################################################################
        # remove noise from image
        #######################################################################
        #gray = cv2.GaussianBlur(gray, (5, 5), 0)
        gray = cv2.blur(gray, (3, 3))
        #gray = cv2.medianBlur(gray, 5)
        cv2.imshow("noise removal", gray)

        #######################################################################
        # update background history, and background average
        #######################################################################
        history_length = get_trackbar_pos("HistoryLenght")
        history_length = 1 if history_length == 9 else history_length
        if prev_history_length != history_length:
            rb = RingBuffer(history_length)
            prev_history_length = history_length
        rb.push(gray.astype(np.float))

        history = rb.buffer
        gray_background = (sum(history) / len(history)).astype(np.uint8)
        cv2.imshow("background", gray_background)

        #######################################################################
        # do background substraction
        #######################################################################
        image_delta = abs(
            gray.astype(np.int8) - gray_background.astype(np.int8))
        image_delta = image_delta.astype(np.uint8)
        delta_threshold = get_trackbar_pos("DeltaThreshold")
        _, image_delta = cv2.threshold(image_delta, delta_threshold, 255,
                                       cv2.THRESH_BINARY)
        cv2.imshow("Vishnus Detection", image_delta)

        #######################################################################
        # open image
        #######################################################################
        size = get_trackbar_pos("MorphOpsSize")
        size = 1 if size == 0 else size
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size))
        iterations = get_trackbar_pos("Iterations")
        iterations = 1 if size == 0 else iterations
        image_delta = cv2.morphologyEx(image_delta,
                                       cv2.MORPH_OPEN,
                                       kernel,
                                       iterations=iterations)

        #######################################################################
        # dilate image
        #######################################################################
        element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
        image_delta = cv2.dilate(image_delta, element)
        cv2.imshow("image_delta_open", image_delta)

        #######################################################################
        # Detect if Motion Alarm is to be triggered
        # hold off for 5 seconds until image stabilized
        #######################################################################
        # import pdb; pdb.set_trace()

        if alarm_hold_time < time.time():
            delta_percentage = 100 * np.count_nonzero(
                image_delta) / image_delta.size
            alarm_threshold = get_trackbar_pos("AlarmThreshold")

            if delta_percentage > alarm_threshold and not intrusion_detected:
                t = threading.Thread(target=run_alarm)
                t.start()
                intrusion_detected = True
                #import pdb;pdb.set_trace(100)

        #######################################################################
        # find and draw contours
        #######################################################################
        src, contours, hierarchy = cv2.findContours(image_delta, cv2.RETR_TREE,
                                                    cv2.CHAIN_APPROX_SIMPLE)

        print("num countours found = %s" % (len(contours)))
        cv2.drawContours(src, contours, -1, (0, 255, 0), -1)

        ###########################################################################
        # blob detection: detect blobs in image
        ###########################################################################
        pass

        #######################################################################
        # image info
        #######################################################################
        # import pdb; pdb.set_trace()
        if alarm_hold_time < time.time():
            pos = (5, 100)
            info = "motion_rate = %0.2f, threshold = %0.2f" % (
                delta_percentage, alarm_threshold)
            cv2.putText(src,
                        info,
                        pos,
                        cv2.FONT_HERSHEY_SIMPLEX,
                        0.7, (255, 255, 255),
                        thickness=6,
                        lineType=cv2.LINE_AA)

        #######################################################################
        # display video processing output
        #######################################################################

        cv2.imshow("src", src)

        #######################################################################
        # calculate elapsed time
        #######################################################################
        elapsed_time = time.time() - start_time
        print("processing time = %.2sms, frame rate = %dfps" %
              (elapsed_time * 1000, refresh_time))

        #######################################################################
        # cv2.waitkey expects a value that corresponds to the msecs to wait
        # which finally defines the frame rate of video.
        #######################################################################
        key = cv2.waitKey(refresh_time)

        #######################################################################
        # stop video processing if user press ESC key
        #######################################################################
        if key == 27:
            vc.release()
            cv2.destroyAllWindows()
            break
Ejemplo n.º 27
0
from ringbuffer import RingBuffer

rb = RingBuffer(5)
print(len(rb))
print(list(rb))
Ejemplo n.º 28
0
 def __init__(self, logger):
     self.ringbuffer = RingBuffer(logger)
     self.newpoints = 0
     self.delay_samples = 0
Ejemplo n.º 29
0
def processing_thread(input_audio, player_track, accompaniment_track,
                      update_queue, test_dict):

    # Algorithm initial conditions
    note_detected = False
    note_time = 0
    note_freq = -1
    time = 0
    detected_notes = RingBuffer(10)
    init_zi = True

    # Heinous hack
    Fs = 44100

    # Low pass filter parameters
    filter_cutoff = 30.0
    filter_order = 4

    # Design the filter
    [
        filter_b,
        filter_a,
    ] = signal.bessel(filter_order, [filter_cutoff / (Fs / 2.0)],
                      btype='low',
                      analog=False)

    # Filter initial conditions
    zi_initial = signal.lfilter_zi(filter_b, filter_a)

    # Load the preprocessed notes written by preprocessSong.m
    chunks = np.loadtxt('WriteDir/playerNotes.txt', delimiter='\t', skiprows=1)

    # Make relative chunks (difference in time, ratio in frequency)
    # rel_times = np.diff(chunks[:, 0])
    # rel_freqs = chunks[1:, 1]/chunks[0:-1, 1]
    # rel_chunks = np.c_[rel_times, rel_freqs]

    while True:
        # Get next chunk of data from the input_audio queue
        song_chunk = input_audio.get()

        # Initialize the filter value
        if init_zi:
            zi = zi_initial * song_chunk[0]
            init_zi = False

        # Detect song notes
        test_dict['time'] = time
        time += float(song_chunk.size) / Fs / 2
        id_notes_dict = detect_notes(song_chunk, Fs, filter_b, filter_a, zi,
                                     note_detected, note_time, test_dict)

        # Update some of the values from the function
        note_detected = id_notes_dict['note_detected']
        note_time_prev = note_time
        note_time = id_notes_dict['note_time']
        zi = id_notes_dict['zi']
        zi = zi_initial * zi

        # If the note time has changed, a new note was detected, so updated the note_freq
        if note_time is not note_time_prev:
            note_freq_prev = note_freq
            note_freq = id_notes_dict['note_freq']

            note = np.array([[note_time, note_freq]])
            detected_notes.extend(note)

            # Need at least two note detections since we are working with relative frequencies/timings
            if note_freq_prev is not -1:
                # rel_note = np.array([[note_time - note_time_prev, note_freq/note_freq_prev]])
                # print(detected_notes.get())
                # Find chunk location
                # chunk_location = find_location(detected_notes, rel_chunks)
                chunk_location = find_location(detected_notes, chunks)

                # Set position/tempo of the update
                position = chunk_location
                update = OutputUpdate(position, 1.0)
                update_queue.put(update)
Ejemplo n.º 30
0
 def set_sampling_rate(self, sampling_rate):
     self._buffer.clear()
     self._buffer = RingBuffer(
         maxlen=int(Settings.DETECTION_BUFFER * sampling_rate)
     )