Write a program to capture an image using camera and display it.


To capture an image using a camera and display it, we can use the OpenCV library in Python. Here's an example program:

python
import cv2 # create a VideoCapture object to capture the video from the default camera cap = cv2.VideoCapture(0) # check if camera opened successfully if not cap.isOpened(): print("Error opening video stream or file") # read the video stream and display the frames while cap.isOpened(): ret, frame = cap.read() if ret: # display the captured frame cv2.imshow('Frame', frame) # press 'q' to exit the program if cv2.waitKey(25) & 0xFF == ord('q'): break else: break # release the video capture object and close all windows cap.release() cv2.destroyAllWindows()


In this program, we first create a VideoCapture object to capture the video from the default camera (which is usually the built-in webcam). We check if the camera opened successfully using the isOpened() function.

Then, we read the video stream using the read() function, which returns a boolean value ret to indicate whether the frame was successfully read and the frame itself as a numpy array frame. We display the captured frame using the imshow() function, and we use the waitKey() function to wait for a key press. If the key pressed is 'q', we break out of the loop and exit the program.

Finally, we release the VideoCapture object and close all windows using the release() and destroyAllWindows() functions, respectively.