Kivy Camera免费资源问题

Kivy Camera free resources issue

我想在我的 Android 应用程序中使用相机拍摄照片和扫描条码。我在kv中添加了它:

<CameraForm>:
    FloatLayout:
        Camera:
            id: camera
            size_hint: (1, 0.8)
            pos_hint: {"center_x": 0.5, "top": 0.95}
            canvas.before:
                PushMatrix
                Rotate:
                    angle: -90 if app.isAndroid() else 0
                    origin: self.center
            canvas.after:
                PopMatrix

        MDRaisedButton:
            text: "Capture"
            size_hint: (None, None)
            height: "40dp"
            pos_hint: {"x": 0.2, "top": 0.1}
            on_press: root.capturePhoto()

和python代码:

class CameraForm(Screen):
    def __init__(self, *args, **kwargs):
        super(CameraForm, self).__init__(*args, **kwargs)
        self.fileName = None
        self.camera = None

    def initCamera(self):
        self.camera = self.ids.camera
        self.camera.resolution = (720, 480)
        self.camera.keep_ratio = True
        self.camera.play = True
        self.camera.allow_stretch = True

    def on_enter(self, *args):
        self.initCamera()

    def capturePhoto(self):
        imgTime = time.strftime("%Y%m%d_%H%M%S")
        self.fileName = MDApp.get_running_app().imagePath + "IMG_{}.png".format(imgTime)  # store image file
        self.camera.export_to_png(self.fileName)
        msgBox = MessageBox()
        msgBox.showMsg("Information", "Image has been successfully captured!", "OK", False)

我有类似的代码让相机扫描条码。问题是当我尝试从相机切换到条形码相机时,我遇到了以下问题:

[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1113) SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072873821
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1125) SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072873821
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072873821
[ERROR  ] [OpenCV      ] Couldn't get image from Camera
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 144, in _update
    self._buffer = frame.imageData
AttributeError: 'NoneType' object has no attribute 'imageData'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 148, in _update
    self._buffer = frame.reshape(-1)
AttributeError: 'NoneType' object has no attribute 'reshape'
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638
[ERROR  ] [OpenCV      ] Couldn't get image from Camera
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 144, in _update
    self._buffer = frame.imageData
AttributeError: 'NoneType' object has no attribute 'imageData'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 148, in _update
    self._buffer = frame.reshape(-1)
AttributeError: 'NoneType' object has no attribute 'reshape'

然后应用程序崩溃了。所以,我认为它需要释放Camera资源。

def on_leave(self, *args):
    self.camera.stop()

当我尝试离开相机屏幕时报告错误:

AttributeError: 'Camera' object has no attribute 'stop'

但是来自 kivy 文档:https://kivy.org/doc/stable/api-kivy.core.camera.html#kivy.core.camera.CameraBase.stop

stop() Added in 1.0.0 Release the camera

那么,为什么 stop() 不适用于 Camera?如何释放 Camera 资源?谢谢你的帮助。

kivy.core.camera.CameraBase class 有一个 stop() 方法,但是 Camera 小部件(在您的 .kv 文件中)是 kivy.uix.camera.Camera class 并且它没有 stop() 方法。

如果要停止摄像头,可以使用Cameraplay属性。 Camera's doc.

否则你可以使用self.camera._camera直接访问Camera中的CoreCamera实例(但我不确定是否推荐)

我建议你看看Camera sources for a better understanding, especially line 102 and the definition of on_play()