├── thermalplayer.gif ├── rpi3_mlx90640_thermalplayer.jpeg ├── README.md ├── LICENSE ├── pixread.py ├── .gitignore ├── main.py └── mlxread.py /thermalplayer.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/9nut/thermalplayer/HEAD/thermalplayer.gif -------------------------------------------------------------------------------- /rpi3_mlx90640_thermalplayer.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/9nut/thermalplayer/HEAD/rpi3_mlx90640_thermalplayer.jpeg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Raspberry Pi Thermal-Visual Player 2 | 3 | A simple Python3 player that scales and blends the output of an Adafruit 4 | MLX90640 thermal camera with the Pi camera output into one output stream. 5 | MLX90640 has a resolution of 32×24 pixels. 6 | 7 | ![example output animated gif](https://github.com/9nut/thermalplayer/blob/master/thermalplayer.gif?raw=true) 8 | 9 | ### Run 10 | ``` 11 | $ python main.py 12 | ``` 13 | 14 | ### Notes 15 | On a Raspberry Pi 3 B+ thermal camera, a capture rate higher than 8Hz usually 16 | fails. When running both the MLX and the Pi camera reader threads, the camera 17 | thread should limit itself to 10 frames/sec to avoid a similar _too many 18 | retries_ errors. 19 | 20 | ### License 21 | MIT 22 | 23 | ### Authors 24 | Skip Tavakkolian 25 | 26 | ### Pictures 27 | 28 | ![RPI3B+ with MLX90640](https://github.com/9nut/thermalplayer/blob/master/rpi3_mlx90640_thermalplayer.jpeg?raw=true) 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Skip Tavakkolian 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /pixread.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Camera capture using OpenCV. This class provides 3 | the basic functionality to run an object of the 4 | type in its own thread. Each captured frame is forwarded 5 | to a reciever using the Signal/Slot mechanism. 6 | ''' 7 | import cv2 8 | import sys 9 | 10 | from PyQt5.QtCore import QObject, QThread, Qt, pyqtSignal, pyqtSlot 11 | from PyQt5.QtGui import QImage, QPixmap 12 | 13 | class VidThread(QObject): 14 | changePixmap = pyqtSignal(QPixmap) 15 | go = pyqtSignal() 16 | width = 0 17 | height = 0 18 | mirror = False 19 | 20 | def __init__(self): 21 | super().__init__() 22 | self.go.connect(self.run) 23 | 24 | @pyqtSlot() 25 | def run(self): 26 | cap = cv2.VideoCapture(0) 27 | print("VidThread") 28 | while True: 29 | ret, frame = cap.read() 30 | if ret: 31 | if self.mirror: 32 | frame = cv2.flip(frame, 1) 33 | 34 | # img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 35 | img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 36 | # h, w, ch = img.shape 37 | h, w = img.shape 38 | ch = 1 39 | stride = w * ch 40 | 41 | # qimg = QImage(img.data, w, h, stride, QImage.Format_RGB888) 42 | qimg = QImage(img.data, w, h, stride, QImage.Format_Grayscale8) 43 | qpix = QPixmap.fromImage(qimg) 44 | qpix = qpix.scaled(self.width, self.height, Qt.KeepAspectRatio) 45 | self.changePixmap.emit(qpix) 46 | 47 | # Without the wait, on RPi3 we get 'too many retries' error 48 | QThread.msleep(100) 49 | 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A simple player that mixes the Pi camera output with the mlx90640 thermal 3 | camera output into one stream. Each capture is run in its own thread and 4 | their outputs (received using Signal/Slot mechanism) are combined in the 5 | player thread. The refersh happends on the receiver of the Pi camera since 6 | it has a faster capture rate. A mutex is used to serialize access to thermal 7 | image pixmap. 8 | ''' 9 | import sys 10 | import threading 11 | 12 | from PyQt5.QtWidgets import QWidget, QLabel, QApplication 13 | from PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlot, QPoint 14 | from PyQt5.QtGui import QPixmap, QPainter 15 | 16 | from pixread import VidThread 17 | from mlxread import MLXThread 18 | 19 | class ThermalPlayer(QWidget): 20 | def __init__(self): 21 | super().__init__() 22 | self.title = 'Thermal Cam' 23 | self.left = 50 24 | self.top = 50 25 | self.leftmargin = 100 26 | self.topmargin = 50 27 | self.width = 640 28 | self.height = 480 29 | self.heatpix = QPixmap(640,480) 30 | self.heatpix.fill(Qt.transparent) 31 | self.campix = None 32 | self.heatpixlock = threading.Lock() 33 | self.initUI() 34 | 35 | 36 | @pyqtSlot(QPixmap) 37 | def setImage(self, pixmap): 38 | # Currently campix isn't used, but if used 39 | # it needs to be deep copied. 40 | self.campix = pixmap.copy() 41 | 42 | # Image compositing 43 | dispix = pixmap 44 | painter = QPainter(dispix) 45 | painter.setRenderHint(QPainter.Antialiasing) 46 | # painter.setCompositionMode(QPainter.CompositionMode_Plus) 47 | painter.setCompositionMode(QPainter.CompositionMode_Screen) 48 | # painter.setCompositionMode(QPainter.CompositionMode_HardLight) 49 | # painter.setCompositionMode(QPainter.CompositionMode_SourceAtop) 50 | 51 | # setHeat callback also accesses heatpix 52 | with self.heatpixlock: 53 | painter.drawPixmap(QPoint(), self.heatpix) 54 | painter.end() 55 | 56 | self.label.setPixmap(dispix) 57 | 58 | 59 | @pyqtSlot(QPixmap) 60 | def setHeat(self, pixmap): 61 | # setImage callback also accesses heatpix 62 | with self.heatpixlock: 63 | self.heatpix = pixmap.copy() 64 | 65 | 66 | def initUI(self): 67 | self.setWindowTitle(self.title) 68 | self.setGeometry(self.left, self.top, self.width, self.height) 69 | self.resize(self.width+2*self.leftmargin,self.height+2*self.topmargin) 70 | 71 | self.label = QLabel(self) 72 | self.label.move(self.leftmargin,self.topmargin) 73 | self.label.resize(self.width, self.height) 74 | 75 | self.show() 76 | 77 | 78 | if __name__ == '__main__': 79 | app = QApplication(sys.argv) 80 | myapp = ThermalPlayer() 81 | 82 | print("Video Thread") 83 | vthread = QThread() 84 | vthread.start() 85 | vth = VidThread() 86 | vth.width = myapp.width 87 | vth.height = myapp.height 88 | vth.mirror = True 89 | vth.changePixmap.connect(myapp.setImage) 90 | vth.moveToThread(vthread) 91 | vth.go.emit() 92 | 93 | print("MLX Thread") 94 | mlxthread = QThread() 95 | mlxthread.start() 96 | mlxt = MLXThread() 97 | mlxt.changeHeatmap.connect(myapp.setHeat) 98 | mlxt.moveToThread(mlxthread) 99 | mlxt.go.emit() 100 | 101 | sys.exit(app.exec_()) 102 | -------------------------------------------------------------------------------- /mlxread.py: -------------------------------------------------------------------------------- 1 | """ 2 | Image capture using Adafruit MLX90640 thermal camera. 3 | This class provides the structure needed to run the MLX reader 4 | in its own thread. The captured frame is forwarded to a receiver 5 | using the Signal/Slot mechanism. The utility functions and 6 | heatmap coefficients come from Adafruit's example code. 7 | """ 8 | 9 | import os 10 | import math 11 | import time 12 | import board 13 | import busio 14 | 15 | from PIL import Image 16 | from PIL.ImageQt import ImageQt 17 | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot 18 | from PyQt5.QtGui import QPixmap 19 | 20 | import adafruit_mlx90640 21 | 22 | #some utility functions 23 | def constrain(val, min_val, max_val): 24 | return min(max_val, max(min_val, val)) 25 | 26 | def map_value(x, in_min, in_max, out_min, out_max): 27 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min 28 | 29 | def gaussian(x, a, b, c, d=0): 30 | return a * math.exp(-(x - b)**2 / (2 * c**2)) + d 31 | 32 | def gradient(x, width, cmap, spread=1): 33 | width = float(width) 34 | r = sum([gaussian(x, p[1][0], p[0] * width, width/(spread*len(cmap))) for p in cmap]) 35 | g = sum([gaussian(x, p[1][1], p[0] * width, width/(spread*len(cmap))) for p in cmap]) 36 | b = sum([gaussian(x, p[1][2], p[0] * width, width/(spread*len(cmap))) for p in cmap]) 37 | r = int(constrain(r*255, 0, 255)) 38 | g = int(constrain(g*255, 0, 255)) 39 | b = int(constrain(b*255, 0, 255)) 40 | return r, g, b 41 | 42 | class MLXThread(QObject): 43 | #low range of the sensor (this will be black on the screen) 44 | MINTEMP = 20. 45 | #high range of the sensor (this will be white on the screen) 46 | MAXTEMP = 50. 47 | #how many color values we can have 48 | COLORDEPTH = 1000 49 | heatmap = ( 50 | (0.0, (0, 0, 0)), 51 | (0.20, (0, 0, .5)), 52 | (0.40, (0, .5, 0)), 53 | (0.60, (.5, 0, 0)), 54 | (0.80, (.75, .75, 0)), 55 | (0.90, (1.0, .75, 0)), 56 | (1.00, (1.0, 1.0, 1.0)), 57 | ) 58 | changeHeatmap = pyqtSignal(QPixmap) 59 | go = pyqtSignal() 60 | 61 | def __init__(self): 62 | super().__init__() 63 | self.go.connect(self.run) 64 | 65 | @pyqtSlot() 66 | def run(self): 67 | print("MLXThread") 68 | colormap = [0] * self.COLORDEPTH 69 | for i in range(self.COLORDEPTH): 70 | colormap[i] = gradient(i, self.COLORDEPTH, self.heatmap) 71 | 72 | i2c = busio.I2C(board.SCL, board.SDA) 73 | mlx = adafruit_mlx90640.MLX90640(i2c) 74 | mlx.refresh_rate = adafruit_mlx90640.RefreshRate.REFRESH_8_HZ 75 | frame = [0] * 768 76 | 77 | while True: 78 | # stamp = time.monotonic() 79 | try: 80 | mlx.getFrame(frame) 81 | except ValueError: 82 | print("ValueError") 83 | continue # these happen, no biggie - retry 84 | 85 | # print("Read 2 frames in %0.2f s" % (time.monotonic()-stamp)) 86 | 87 | pixels = [0] * 768 88 | for i, pixel in enumerate(frame): 89 | coloridx = map_value(pixel, self.MINTEMP, self.MAXTEMP, 0, self.COLORDEPTH - 1) 90 | coloridx = int(constrain(coloridx, 0, self.COLORDEPTH-1)) 91 | pixels[i] = colormap[coloridx] 92 | 93 | img = Image.new('RGB', (32,24)) 94 | img.putdata(pixels) 95 | img = img.resize((640, 480), Image.BICUBIC) 96 | img = ImageQt(img) 97 | pixmap = QPixmap.fromImage(img) 98 | self.changeHeatmap.emit(pixmap) 99 | 100 | --------------------------------------------------------------------------------