覆盖picamera预览上的透明png很难看

时间:2016-02-29 12:29:08

标签: python

我有一个带摄像头模块的树莓派,我试图在相机预览上覆盖透明的PNG。

我使用了http://picamera.readthedocs.org/中的示例代码(将tostring()更改为tobytes(),因为它已被弃用):

import picamera
from PIL import Image
from time import sleep

with picamera.PiCamera() as camera:
    camera.resolution = (1280, 720)
    camera.vflip = True
    camera.start_preview()

    # Load the arbitrarily sized image
    img = Image.open('3.png')
    # Create an image padded to the required size with
    # mode 'RGB'
    pad = Image.new('RGB', (
        ((img.size[0] + 31) // 32) * 32,
        ((img.size[1] + 15) // 16) * 16,
        ))
    # Paste the original image into the padded one
    pad.paste(img, (0, 0))

    # Add the overlay with the padded image as the source,
    # but the original image's dimensions
    o = camera.add_overlay(pad.tobytes(), size=img.size)
    # By default, the overlay is in layer 0, beneath the
    # preview (which defaults to layer 2). Here we make
    # the new overlay semi-transparent, then move it above
    # the preview
    o.alpha = 128
    o.layer = 3

    # Wait indefinitely until the user terminates the script
    while True:
        sleep(1)

..但叠加层不可读,文字上方有一个正方形。

这就是图像本身的样子: enter image description here

这就是叠加在相机预览上时的样子: enter image description here

1 个答案:

答案 0 :(得分:0)

Deon

您需要将图片设为RGBA,然后将图片粘贴两次:

pad = Image.new('RGBA',
        ((img.size[0] + 31) // 32) * 32,
        ((img.size[1] + 15) // 16) * 16,
        ))

pad.paste(img, (0, 0), img)

第三个参数是透明度蒙版。它将从您的图像中读取Alpha并将其应用。