webcam cv2

import cv2

cap = cv2.VideoCapture(0)

# Check if the webcam is opened correctly
if not cap.isOpened():
    raise IOError("Cannot open webcam")

while True:
    ret, frame = cap.read()
    frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
    cv2.imshow('Input', frame)

    c = cv2.waitKey(1)
    if c == 27:
        break

cap.release()
cv2.destroyAllWindows()

Here is what the above code is Doing:
1. We create a VideoCapture object. Its argument can be either the device index or the name of a video file. Device index is just the number to specify which camera. Normally one camera will be connected (as in my case). So I simply pass 0 (or -1). You can select the second camera by passing 1 and so on.
2. Then we check if the webcam is opened correctly. If not, print an error message.
3. We capture the frame-by-frame.
4. We resize the frame to a smaller size so that our processor can handle the frames in real-time.
5. We show the frame on the screen.
6. If the user presses the Esc key, we break out of the loop.
7. We release the webcam and destroy all the windows inside which images were displayed.