简体   繁体   中英

Why cv2.imwrite lags 1 step?

My code:

import cv2

cap = cv2.VideoCapture(0)
cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
while True:
    key = cv2.waitKey(0) & 0xFF
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    if key == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break
    if key == ord('c'):
        cv2.imwrite('capture.jpg', frame)
cap.release()
cv2.destroyAllWindows()
  1. I run this code.
  2. It shows the gray display.
  3. I point the camera at an object and press the 'c' key.
  4. It shows not the object image but the image of what the camera pointed at when I run the code, and saves it.
  5. I point the camera at somewhere else and press 'c' key agein.
  6. It shows the image of the object which it saw at 3. and save it.

The camera lags 1 step. Why?

This could be to do with a lack of cv::waitKey(0) and the window is not getting updated, although this is odd.

Try adding a cv::waitKey command after imshow like this

import cv2

cap = cv2.VideoCapture(0)
cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
while True:
    key = cv2.waitKey(0) & 0xFF
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    cv2.waitKey(0)
    if key == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break
    if key == ord('c'):
        cv2.imwrite('capture.jpg', frame)
cap.release()
cv2.destroyAllWindows()

I think it might be this as when you do the imwrite you are effectively breaking out of the while loop (albeit slightly) to do something else with opencv.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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