希望您做得很好,我正在尝试提供“无头”摄像头服务,但是camera._camera.bind()
似乎无法正常运行,除非它是LayOut的一部分,这是“带有GUI的几乎最小的摄像头示例”,它是工作:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
import PIL
from kivy.uix.camera import Camera
Builder.load_string('''
<CameraClick>:
orientation: 'vertical'
ToggleButton:
text: 'Play'
on_press: root.camera.play = not root.camera.play
size_hint_y: None
height: '48dp'
Button:
text: 'Capture'
size_hint_y: None
height: '48dp'
on_press: root.capture()
''')
class CameraClick(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.camera = Camera(play=False, resolution=(640, 480))
self.camera._camera.bind(on_texture=self.capture)
def capture(self, instance=None):
'''
Function to capture the images and give them the names
according to their captured time and date.
'''
camera = instance or self.camera
print(type(camera), camera)
texture = camera.texture
image_data = texture.pixels
size = texture.size
fmt = texture.colorfmt.upper()
timestr = time.strftime("%Y%m%d_%H%M%S")
pil_image = PIL.Image.frombytes(mode=fmt, size=size, data=image_data)
pil_image.save("IMG_{}.png".format(timestr))
print("Captured")
class TestCamera(App):
def build(self):
return CameraClick()
TestCamera().run()
这是我在没有GUI的情况下无法正常工作的最小示例:
from kivy.uix.camera import Camera
import time
import PIL
def capture(instance):
camera = instance
texture = camera.texture
image_data = texture.pixels
size = texture.size
fmt = texture.colorfmt.upper()
timestr = time.strftime("%Y%m%d_%H%M%S")
pil_image = PIL.Image.frombytes(mode=fmt, size=size, data=image_data)
pil_image.save("IMG_{}.png".format(timestr))
print("Captured")
c = Camera(play=False, resolution=(640, 480))
c._camera.bind(on_texture=capture)
c.play = True
print("Taking 5 seconds of photos...")
sleep(5)
print("Turning off taking photos")
c.play = False
因此,在GUI示例中,当我单击播放时,这很有效,这很简单,camera.play = True
,而当我在没有GUI的最小Camera上执行camera.play = True
时,将永远不会调用捕获功能。 / p>
我在做什么错了?
编辑:来自Matham(请参阅github评论):看来您正在阻止kivy主线程。您无法以“无头”模式运行kivy,因为gui始终需要运行,并且主线程无法被阻止,https://github.com/kivy/kivy/issues/6272#issuecomment-486489264
所以我认为我需要使用pyjnius实现摄像头