简体   繁体   English

如何使用 opencv 通过键盘输入捕获图像?

[英]How to capture an image by keyboard input using opencv?

I wanted to capture an image directly from my camera by keyboard input.我想通过键盘输入直接从我的相机捕捉图像。 For example, when I press 'r', the camera takes a picture of what it sees.例如,当我按“r”时,相机会拍下它所看到的照片。 Here's my code:这是我的代码:

import cv2 as cv
import time

cap = cv.VideoCapture(0)

while True:
    _, img = cap.read()

    cv.imshow('original', img)

    if cv.waitKey(1) == ord('q'):
        break
    elif cv.waitKey(1) == ord('r'):
        cv.imwrite('data_{}.jpg'.format(time.time()), img)
        print('saving an image')
        continue
    else:
        continue

cap.release()
cv.destroyAllWindows()

This code is actually working but not that good.这段代码实际上是有效的,但不是那么好。 Sometimes, when I press 'r' it not saving any image into my directory.有时,当我按“r”时,它不会将任何图像保存到我的目录中。 How could I improve this code so whenever I press 'r' it's certainly saving an image?我怎样才能改进这段代码,所以每当我按“r”时,它肯定会保存图像?

You're supposed to capture a key and then check its value.你应该捕获一个键,然后检查它的值。

while True:
    key = cv.waitKey(1)
    if key == ord('q'):
        break
    elif key == ord('r'):
        # do your stuff here
        pass

The way you've done it transverses the conditional blocks with a new key press at a time.您完成它的方式一次通过一个新的按键来跨越条件块。 Let's say you first press 'r'.假设您先按“r”。 The loop is currently at if cv.waitKey(1) == ord('q') , which evaluates false, so it continues to the next check.循环当前位于if cv.waitKey(1) == ord('q') ,其评估结果为 false,因此它继续进行下一次检查。 By this time you're not pressing anything, so cv.waitKey(1) will return -1 and your check for 'r' will be false.到这个时候你没有按下任何东西,所以cv.waitKey(1)将返回 -1 并且你对 'r' 的检查将是错误的。 And on and on you go.还有你 go。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM