在Kivy画布上显示PIL图像

时间:2018-08-12 05:53:09

标签: python kivy python-imaging-library

我找不到有关如何在Kivy画布上显示PIL图像的任何文档。

Rectangle(source=image) give TypeError: 'Image' object has no attribute '__getitem__'

由于其他图像操作,我需要使用枕头图像。我什至试图将图像加载到纹理中,然后将纹理应用到画布上,但是后来我不知道如何将格式转换为兼容的格式。关于如何在纹理和画布上加载图像的Kivy文档几乎不存在。

1 个答案:

答案 0 :(得分:3)

在下面的示例中,它演示了如何使用PIL Image处理图像并将其显示为Kivy Image小部件的 source texture canvas

示例

main.py

from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.image import CoreImage
from kivy.lang import Builder

from PIL import Image

kv = Builder.load_string('''
#:kivy 1.11.0

<RootWidget>:
    img: img
    img3: img3
    img4: img4
    do_default_tab: False

    TabbedPanelItem:
        text: 'PIL Image'

        Screen:
            RelativeLayout:
                Image:
                    id: img
                    pos_hint: {"left": 1, 'bottom': 1}
                    size_hint: 0.5, 1
                    allow_stretch: True

            RelativeLayout:
                Image:
                    id: img3
                    pos_hint: {"right": 1, 'bottom': 1}
                    size_hint: 0.5, 1
                    allow_stretch: True

    TabbedPanelItem:
        text: 'canvas'

        Screen:
            FloatLayout:
                Image:
                    id: img4
                    keep_data: True
                    allow_stretch: True
                    canvas.before:
                        Color:
                            rgba: 0, 0, 0, 1  # Black
                        Rectangle:
                            pos: self.pos
                            size: self.size


''')


class RootWidget(TabbedPanel):

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        iw = Image.open("./DSC08518.JPG")   # Use PIL.Image
        iw.save('./phase.jpg')
        gray = iw.convert('1')
        gray.save('./gray_im.jpg')
        self.img.source = './phase.jpg'
        self.img3.texture = CoreImage('./gray_im.jpg').texture
        self.img4.source = './gray_im.jpg'


class KivyPILApp(App):
    title = "Kivy & PIL Demo"

    def build(self):
        return RootWidget()


if __name__ == "__main__":
    KivyPILApp().run()

输出

Img01 - Kivy Image Source & Texture Img02 - Kivy Image canvas