import board
import busio
import numpy as np
import adafruit_mlx90640
import cv2
from picamera2 import Picamera2
import time
# ---- Set up MLX90640 (Thermal Camera) ----
i2c = busio.I2C(board.SCL, board.SDA, frequency=400000)
mlx = adafruit_mlx90640.MLX90640(i2c)
mlx.refresh_rate = adafruit_mlx90640.RefreshRate.REFRESH_4_HZ # Keep low to match Pi display
mlx_shape = (24, 32)
# ---- Set up Pi Camera ----
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640, 480)
picam2.preview_configuration.main.format = "RGB888"
picam2.configure("preview")
picam2.start()
time.sleep(1) # Let camera warm up
# ---- Main Loop ----
while True:
try:
# --- Capture RGB Frame ---
rgb_frame = picam2.capture_array()
rgb_small = cv2.resize(rgb_frame, (320, 240))
# --- Capture Thermal Frame ---
frame = [0] * 768
mlx.getFrame(frame)
thermal = np.reshape(frame, mlx_shape)
# Normalize and apply colormap
thermal = np.clip(thermal, 20, 100) # Optional: clip range
norm = cv2.normalize(np.array(thermal), None, 0, 255, cv2.NORM_MINMAX)
thermal_colored = cv2.applyColorMap(np.uint8(norm), cv2.COLORMAP_INFERNO)
thermal_resized = cv2.resize(thermal_colored, (320, 240), interpolation=cv2.INTER_NEAREST)
# --- Combine Views Side by Side ---
combined = np.hstack((rgb_small, thermal_resized))
cv2.imshow("RGB (left) + Thermal (right)", combined)
# --- Break on 'q' ---
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except Exception as e:
print("Error:", e)
cv2.destroyAllWindows()