Achmad Setiawan
Achmad Setiawan

Reputation: 179

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. 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. How could I improve this code so whenever I press 'r' it's certainly saving an image?

Upvotes: 1

Views: 2442

Answers (1)

Reti43
Reti43

Reputation: 9796

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'. The loop is currently at if cv.waitKey(1) == ord('q'), which evaluates false, so it continues to the next check. By this time you're not pressing anything, so cv.waitKey(1) will return -1 and your check for 'r' will be false. And on and on you go.

Upvotes: 3

Related Questions