Search code examples
python-3.xraspberry-pipicamera

How to place overlay on top of picamera preview


So I have this bit of code almost working but the overlay takes over the entire HDMI output (fullscreen) when I only want it to appear on the camera preview window.

import picamera
import time

image_folder="../images/"

with picamera.PiCamera() as camera:
                camera.start_preview()
                camera.preview.window=(0,0, 750, 400)
                camera.preview.fullscreen=False

                # Overlay
                img = Image.open(image_folder+'cam_overlay.png')
                pad = Image.new('RGBA', (
                    ((img.size[0] + 31) // 32) * 32,
                    ((img.size[1] + 15) // 16) * 16,
                    ))
                pad.paste(img, (0, 0))
                o = camera.add_overlay(pad.tobytes(), size=img.size)
                o.alpha = 32
                o.layer = 3
          
                time.sleep(10)
                camera.stop_preview()

Pic included below. Overlay is vertical lines over the whole screen but should only be on the part in the upper left. Pic included below. Overlay is vertical lines over the whole screen but should only be on the part in the upper left.


Solution

  • For anyone encountering this problem, the live preview and overlay act independently using different renderers. You have specified the position of the preview window via

    camera.preview.window=(0,0, 750, 400)
    

    but have not specified the same for the overlay window. This can be done using the same syntax but referencing the overlay itself

    # add the overlay
    o = camera.add_overlay(pad.tobytes(), size=img.size)
    o.fullscreen = False
    
    # specify the position of the overlay window to match the preview
    o.window = (0, 0, 750, 400)
    o.alpha = 32
    o.layer = 3