Exemplo n.º 1
0
Arquivo: spo.py Projeto: EdissonM/RPPG
    def get_filtered(self, array, band):
        processed = np.array(array)
        processed = signal.detrend(processed)
        processed = utils.butter_bandpass_filter(processed,
                                                 0.3,
                                                 2.5,
                                                 self.fps,
                                                 order=3)
        signal_line = processed - smooth(processed, 5)
        signal_line = utils.butter_bandpass_filter(signal_line,
                                                   0.05,
                                                   0.15,
                                                   self.fps,
                                                   order=9)
        analytic_signal = signal.hilbert(signal_line)
        high = np.mean(np.abs(analytic_signal))
        low = np.mean(low_envelope(signal_line))
        d_signal = signal.detrend(signal_line)
        removed = filter(lambda x: low < x < high, d_signal)

        edges = [0, band[0], band[1], band[2], band[3], 0.5 * self.fps]
        taps = signal.remez(3, edges, [0, 1, 0], Hz=self.fps, grid_density=20)
        filttered_color = np.convolve(taps, removed)[len(taps) // 2:]

        return filttered_color
Exemplo n.º 2
0
    def update(self, roi):
        g = utils.extract_color(roi, 1)
        buffer_len = len(self.data_buffer)
        if abs(g - np.mean(self.data_buffer)) > 10 and buffer_len > 99:
            g = self.data_buffer[-1]

        self.times.append(time.time() - self.t0)
        self.data_buffer.append(g)
        if buffer_len > self.buffer_size:
            self.data_buffer = self.data_buffer[-self.buffer_size:]
            self.times = self.times[-self.buffer_size:]
            self.beats_per_minute = self.beats_per_minute[-self.buffer_size //
                                                          2:]
            buffer_len = self.buffer_size

        processed = np.array(self.data_buffer)

        if buffer_len == self.buffer_size:
            self.fps = float(buffer_len) / (self.times[-1] - self.times[0])
            even_times = np.linspace(self.times[0], self.times[-1], buffer_len)
            processed = signal.detrend(processed)
            interpolated = np.interp(even_times, self.times, processed)
            interpolated = np.hamming(buffer_len) * interpolated
            norm = interpolated / np.linalg.norm(interpolated)
            raw = np.fft.rfft(norm * 30)
            self.frequency = float(
                self.fps) / buffer_len * np.arange(buffer_len / 2 + 1)
            freqs = 60. * self.frequency
            self.fft = np.abs(raw)**2
            idx = np.where((freqs > 50) & (freqs < 180))
            pruned = self.fft[idx]
            pfreq = freqs[idx]
            self.frequency = pfreq
            self.fft = pruned
            idx2 = np.argmax(pruned)
            self.bpm = self.frequency[idx2]
            self.beats_per_minute.append(self.bpm)
            processed = utils.butter_bandpass_filter(processed,
                                                     0.8,
                                                     3,
                                                     self.fps,
                                                     order=3)
        self.samples = processed
Exemplo n.º 3
0
def cvt_hr(labels, duration, fs, lowcut, highcut, order):
    N = len(labels)
    t = np.linspace(0, duration, N)

    y = utils.butter_bandpass_filter(labels, lowcut, highcut, fs, order)
    # y = cheby2_bandpass_filter(labels, 20, lowcut, highcut, fs, order=4)

    # periodogram
    FFT2 = abs(scipy.fft(y, N))
    f2 = 20 * scipy.log10(FFT2)
    f2 = f2[range(int(N / 2))]  # remove mirrored part of FFT
    freqs2 = scipy.fftpack.fftfreq(N, t[1] - t[0])
    freqs2 = freqs2[range(int(N / 2))]  # remove mirrored part of FFT

    d = np.argmax(f2)

    # Plotting periodogram
    x1 = freqs2[d]
    y1 = max(f2)     

    HeartRate = freqs2[d] * 60
    return HeartRate
Exemplo n.º 4
0
def methodB(Amplit, SamplingFreq, ax, Tstamp):
    High = 10e6
    Low = 1e6

    Time = 1e3 * (np.arange(0, Amplit.size, 1) / SamplingFreq)
    Amplit = utils.butter_bandpass_filter(Amplit,
                                          Low,
                                          High,
                                          SamplingFreq,
                                          order=1)

    ax.plot(Time, Amplit)

    # Trimm the vectors around centre
    #TimeAround = np.int(2e3/SamplingFreq)
    #IndexCentre = np.where(Amplit == np.max(Amplit))
    #Time = Time[IndexCentre-TimeAround:IndexCentre+TimeAround]
    #Amplit = Amplit[IndexCentre-TimeAround:IndexCentre+TimeAround]

    mpd = np.int(2e-6 * SamplingFreq)
    #mpd = np.int(200e-9 * SamplingFreq)

    indexes = utils.detect_peaks(Amplit, mpd=mpd)

    #IntegralAround = np.int(1.13e-6 * SamplingFreq)
    #IntegralAround =  np.int(100e-9*SamplingFreq)  Integrals of 200ns
    #indexes = indexes[10:len(indexes)-10]

    Amplit_p = Amplit[indexes]
    Time_p = Time[indexes]
    #ax.plot(Time_p, Amplit_p, '.r', label = Tstamp)

    #Averaging_Window = 5
    #Amplit_p = np.convolve(Amplit_p, np.ones((Averaging_Window,)) / Averaging_Window, mode='valid')
    #Time_p = np.convolve(Time_p, np.ones((Averaging_Window,)) / Averaging_Window, mode='valid')
    return Time_p, Amplit_p
Exemplo n.º 5
0
""
# Source geometry
src_coords = np.empty((1, len(spacing)))
src_coords[0, 0] = xsrc
src_coords[0, 1] = ysrc
src_coords[0, 2] = zsrc

# Build source wavelet
wavelet = np.concatenate((np.load("%swavelet.npy" % geomloc), np.zeros(
    (100, ))))
twave = [i * 1.2 for i in range(wavelet.shape[0])]
tnew = [i * dt for i in range(int(1 + (twave[-1] - tstart) / dt))]
fq = interpolate.interp1d(twave, wavelet, kind='linear')
q_custom = np.zeros((len(time_axis), 1))
q_custom[:len(tnew), 0] = fq(tnew)
q_custom[:, 0] = butter_bandpass_filter(q_custom[:, 0], .005, .030, 1 / dt)
q_custom[:, 0] = 1e1 * q_custom[:, 0] / np.max(q_custom[:, 0])

timer(t0, 'Setup geometry')
t0 = time.time()

""

""
# Model data
info("Starting forward modeling")
tstart = time.time()
d_obs, u, summary1 = forward(model, src_coords, rec_coordinates, q_custom[:,
                                                                          0])
tend = time.time()
timer(t0, 'Run forward')
    def extract_segments_audio(self, box_source, sample_source):
        '''
        Save audio files based on boxed segments
        
        For each boxed segment, extracts the samples from the
        desired times and band-pass filters to select only the desired
        frequencies. Saves each file and creates a row in the csv.

        CSV format:
            FILENAME, TYPE,DURATION_s, LOW-BOUND, HIGH-BOUND, BOUND-UNIT, SOURCE-FILE, EXTRACTOR, EXTRACTION-METHOD, DATE, DEPRECATED, CALL-TYPE
            species_0.wav,audio,<seconds>,<Hz>,<Hz>,Hz,<path-to-source-file>,author,autoboxer,<date>,0,unknown
            
        Inputs:
            box_source: spectrogram that boxes came from
            sample_source: source of samples to extract and filter
        '''
        full_templates_path = os.path.join(self.templates_path, self.species)
        try:
            os.makedirs(full_templates_path)
        except FileExistsError:
            pass

        assert (self.author)

        # Open .csv for segment information
        csv_path = os.path.join(full_templates_path, f'{self.species}.csv')
        if os.path.exists(csv_path):
            mode = 'a'  # append if already exists
        else:
            mode = 'w+'  # make a new file if not
        open_file = open(csv_path, mode)
        writer = csv.writer(open_file)
        if mode == 'w+':  # add a header
            writer.writerow([
                'FILENAME', 'TYPE', 'DURATION_s', 'LOW-BOUND', 'HIGH-BOUND',
                'BOUND-UNIT', 'SOURCE-FILE', 'EXTRACTOR', 'EXTRACTION-METHOD',
                'DATE', 'DEPRECATED', 'CALL-TYPE'
            ])

        # Get bounding boxes and times
        box_source = self.get_spect(box_source)
        bounding_boxes = box_source.freq_samp_boxes
        times = box_source.times
        try:
            assert bounding_boxes is not None
        except AssertionError:
            raise ValueError(
                f'self.{source_label} does not have bounding boxes')

        # Get samples
        samples = self.get_samples(sample_source)

        now = datetime.now()
        date = now.strftime("%Y%m%d")
        # Extract samples for each box
        segment_number = 0
        for idx, box in enumerate(bounding_boxes):
            # Get individual values from box
            high_freq, low_freq, start_sample, end_sample = box

            # Extract those samples from the audio
            segment_samples = samples[start_sample:end_sample]

            # Bandpass filter the samples above and below the box limits
            filtered_samples = utils.butter_bandpass_filter(
                segment_samples, low_freq, high_freq, self.sample_rate)

            # save samples
            filename_to_save = f'{self.species}_{segment_number}'
            segment_number += 1
            detection_filename = self.save_samples_as_wav(
                filtered_samples, full_templates_path, filename_to_save)

            # This only happens if the detection was successfully saved
            if detection_filename is not None:
                # write information to csv
                # account for rounding error in boxing
                if box[2] > len(times) - 1:
                    start_time = times[-1]
                else:
                    start_time = times[box[2]]
                if box[3] > len(times) - 1:
                    end_time = times[-1]
                else:
                    end_time = times[box[3]]
                duration = end_time - start_time

                writer.writerow([
                    f'{filename_to_save}.wav', 'audio', duration, low_freq,
                    high_freq, 'Hz', self.filename, self.author, 'autoboxer',
                    date, 0, 'unknown'
                ])

        open_file.close()
Exemplo n.º 7
0
end = time.time()
print(end - start, len(val_loader))
outputs = torch.cat(outputs)

outputs = (outputs - torch.mean(outputs)) / torch.std(outputs)
outputs = outputs.tolist()

reference_ = torch.cat(reference_)
reference_ = (reference_ - torch.mean(reference_)) / torch.std(reference_)
reference_ = reference_.tolist()

fs = 30
lowcut = 1
highcut = 3

yr = butter_bandpass_filter(outputs, lowcut, highcut, fs, order=4)
yr = (yr - np.mean(yr)) / np.std(yr)

plt.subplots_adjust(right=0.7)
plt.plot(outputs, alpha=0.7, label='wyjście\n sieci')
plt.plot(yr, label='wyjście\n sieci')
plt.plot(reference_, '--', label='referencja\n PPG')

plt.legend(bbox_to_anchor=(1.02, 1),
           loc='upper left',
           borderaxespad=0,
           fontsize='large')
plt.ylabel('Amplituda', fontsize='large', fontweight='semibold')
plt.xlabel('Czas [próbka]', fontsize='large', fontweight='semibold')
plt.grid()
plt.xlim([350, 550])