Use this code to plot the heat map on a live camera video and calculate the tdoa with two simultaneous recordings of my microphones: import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
Definir os parâmetros da hipérbole
a, b = 0, 0 # Coordenadas do primeiro foco
c, d = 2, 0 # Coordenadas do segundo foco
k = 2 # Constante da hipérbole
x_min, x_max = -5, 5
epsilon = 0.1 # Largura da faixa ao redor de y = 0
y_min, y_max = -epsilon, epsilon
resolucao_x = 1000 # Resolução em x
resolucao_y = 500 # Resolução em y
plt.figure(figsize=(12, 6))
plt.contourf(X, Y, Z, levels=100, cmap='hot', norm=plt.cm.colors.LogNorm())
plt.colorbar(label='Valor absoluto da equação da hipérbole')
Plotar a projeção no eixo x
Encontrar os valores de x onde a hipérbole está definida
proj_x = []
for x in x_vals:
# Tentar resolver para y = 0
y = 0
valor_equacao = hiperb_equacao(y, x)
if np.isclose(valor_equacao, 0, atol=1e-3):
proj_x.append(x)
Plotar a projeção no eixo x
plt.plot(proj_x, [0]*len(proj_x), 'b.', markersize=5, label='Projeção no eixo x')
Ajustar o gráfico
plt.title('Heatmap ao Redor da Projeção da Hipérbole no Eixo x')
plt.xlabel('x')
plt.ylabel('y (faixa estreita ao redor de y = 0)')
plt.legend()
plt.grid(False)
plt.show()
Assistant
To help you integrate your hyperbola plotting code with live camera video and calculate the Time Difference of Arrival (TDoA) using two simultaneous microphone recordings, we'll need to make several modifications and additions to your existing code. Below is a step-by-step guide along with the modified code to achieve your goal.
Overview
Capture Live Video Feed: Use OpenCV to access your webcam.
Capture Audio from Two Microphones: Use the sounddevice library to record audio simultaneously from two microphones.
Calculate TDoA: Compute the cross-correlation between the two audio recordings to find the time delay.
Update Hyperbola Parameters: Use the calculated TDoA to adjust the hyperbola representing possible sound source locations.
Overlay Heatmap on Video: Generate a heatmap based on the hyperbola and overlay it onto each frame of the video.
Prerequisites
Make sure you have the following libraries installed:
import numpy as np
import sounddevice as sd
from scipy.signal import correlate
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
import cv2 # OpenCV library for video processing
2. Define Hyperbola Function
We need to adjust your hyperbola equation to accept dynamic k (the TDoA value adjusted for distance).
def record_audio(duration, fs):
# Adjust 'channels' to [1, 2] if your microphones are the first and second channels
recording = sd.rec(int(duration * fs), samplerate=fs, channels=2, dtype='float64')
sd.wait()
mic1 = recording[:, 0]
mic2 = recording[:, 1]
return mic1, mic2
Note: Ensure your sound device supports stereo recording and that each microphone is captured on separate channels. You may need to configure your audio settings accordingly.
def overlay_heatmap_on_frame(frame, heatmap):
# Resize heatmap to match frame size
heatmap_resized = cv2.resize(heatmap, (frame.shape[1], frame.shape[0]))
heatmap_colored = cv2.applyColorMap(heatmap_resized, cv2.COLORMAP_JET)
# Overlay the heatmap onto the frame with some transparency
overlayed_frame = cv2.addWeighted(frame, 0.7, heatmap_colored, 0.3, 0)
return overlayed_frame
7. Main Loop to Capture Video and Update Heatmap
python
def main():
# Camera setup
cap = cv2.VideoCapture(0) # Change to the correct camera index if needed
# Microphone positions (adjust as per your setup)
a, b = 0, 0 # Coordinates of the first microphone
c, d = 2, 0 # Coordinates of the second microphone
# Grid for heatmap calculation
x_min, x_max, x_res = -5, 5, 200
y_min, y_max, y_res = -5, 5, 200
x_vals = np.linspace(x_min, x_max, x_res)
y_vals = np.linspace(y_min, y_max, y_res)
X, Y = np.meshgrid(x_vals, y_vals)
while True:
# 1. Capture frame-by-frame
ret, frame = cap.read()
if not ret:
break
# 2. Record audio
duration = 0.5 # Duration in seconds
fs = 44100 # Sampling rate
mic1, mic2 = record_audio(duration, fs)
# 3. Calculate TDoA
tdoa = calculate_tdoa(mic1, mic2, fs)
k = tdoa_to_distance(tdoa)
# 4. Compute the heatmap based on the new k
Z = hyperbola_equation(X, Y, a, b, c, d, k)
Z_normalized = cv2.normalize(Z, None, 0, 255, cv2.NORM_MINMAX).astype('uint8')
# 5. Overlay heatmap onto the frame
overlayed_frame = overlay_heatmap_on_frame(frame, Z_normalized)
# 6. Display the resulting frame
cv2.imshow('Video with Heatmap', overlayed_frame)
# Exit condition
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()
8. Run the Main Function
python
if __name__ == '__main__':
main()
Additional Notes
Microphone Calibration: Ensure that both microphones are properly calibrated and synchronized. Differences in hardware or drivers can introduce delays that affect the TDoA calculation.
Scaling and Alignment: The heatmap coordinates need to correspond to the real-world positions in the video frame. You may need to apply transformations to align the heatmap correctly.
Performance Optimization: Real-time processing can be computationally intensive. Consider optimizing your code or using more efficient libraries if you encounter performance issues.
Error Handling: Include error handling for cases where the TDoA calculation might fail or produce unrealistic values.
Testing the Code
Before running the code:
Test the audio recording separately to ensure both microphones are capturing audio correctly.
Verify that your camera feed works with OpenCV.
Troubleshooting
Audio Device Errors: If you encounter errors with the sounddevice library, check your audio device settings and ensure that you have the correct device indices.
Incorrect Heatmap Overlay: If the heatmap doesn't align properly with the video, adjust the coordinate mapping between the hyperbola calculation and the video frame dimensions.
High CPU Usage: Processing video and audio simultaneously can be CPU-intensive. Close other applications to free up resources or consider processing at a lower frame rate.
Conclusion
By integrating live video capture, simultaneous audio recording, and real-time processing, this code allows you to visualize the potential sound source locations on your video feed based on the TDoA between two microphones. Adjust the parameters and fine-tune the implementation according to your specific setup and requirements.
Feel free to ask if you need further assistance or clarifications on any part of the code.