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

Discussão em 'Python' iniciado por Stack, Julho 6, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página