with() 语句从 opencv 中的 VideoCapture 读取? [英] with() statement to read from VideoCapture in opencv?

查看:59
本文介绍了with() 语句从 opencv 中的 VideoCapture 读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用 with 语句来访问文件和数据库连接,因为它会在发生错误或文件关闭时自动为我断开连接.

I like using a with statement for accessing files and database connections because it automatically tears down the connection for me, in the event of error or file close.

f = open('file.txt', 'r')
for i in f():
   print(i)
f.close()

对比

with open('file.txt', 'r') as f:
   for i in f:
       print(i)

以下是否有对从相机缓冲区读取的等效改写?:

Is there an equivalent rephrasing for reading from the camera buffer in the following?:

c = cv.VideoCapture(0)    
while(1):
    _,f = c.read()
    cv.imshow('e2',f)
    if cv.waitKey(5)==27:
        cv.waitKey()
        break
c.release()

我试过了:

c = cv.VideoCapture(0)    
while(1):
   with c.read() as _,f:
       cv.imshow('e2',f)
       if cv.waitKey(5)==27:
           cv.waitKey()
           break

---没有运气.看起来拆卸/释放是一种不同的功能.这个成语在这里可行吗?

---with no luck. It looks like the tear-down/release is a different kind of function. Is this idiom possible here?

推荐答案

我不知道 opencv,所以可能有更好的答案——但是你总是可以实现 上下文管理器自己定义 __enter____exit__ 钩子:

I don't know opencv, so there may be a better answer -- but you can always implement the context manager yourself by defining the __enter__ and __exit__ hooks:

class MyVideoCapture(cv.VideoCapture):
    def __enter__(self):
        return self
    def __exit__(self, *args):
        self.release()

用法如下:

with MyVideoCapture(0) as c:    
    while(1):
        _,f = c.read()
        cv.imshow('e2',f)
        if cv.waitKey(5)==27:
            cv.waitKey()
            break

点击break语句后资源会被释放.

and the resource will be released after you hit the break statement.

根据您的评论,看起来 opencv 在这里做了一些时髦的事情.您还可以创建一个自定义类来包装 VideoCapture 实例:

Based on your comment, it looks like opencv is doing something funky here. You can also create a custom class to wrap the VideoCapture instance:

class VideoCaptureWrapper(object):
    def __init__(self, *args, **kwargs):
        self.vid_steam = VideoCapture(*args, **kwargs):
    def __enter__(self):
        return self
    def __exit__(self, *args):
        self.vid_stream.release()

这里的用法是:

with VideoCaptureWrapper(0) as c:    
    while(1):
        _,f = c.vid_stream.read()
        cv.imshow('e2',f)
        if cv.waitKey(5)==27:
            cv.waitKey()
            break

这篇关于with() 语句从 opencv 中的 VideoCapture 读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆