Search code examples
pythonnumpyopencvvideo-streamingcrop

TypeError with VideoCapture Crop


I have been trying to crop a video frame using numpy slicing, as suggested by other answers to how to crop a video via OpenCV. I set up my live video capture as follows:

vs = VideoCapture(1)
vs.set(cv2.CAP_PROP_FRAME_WIDTH,100)
vs.set(cv2.CAP_PROP_FRAME_HEIGHT,100)

I then create a while loop to loop over the frames from the video stream:

while True:
   frame = vs.read()
   cropped = frame[160:450, 170:470]

When I run the script, however, an error is returned that states:

cropped = frame[160:450, 170:470]

TypeError: tuple indices must be integers or slices, not tuple

Does anyone have a solution to this issue?


Solution

  • You called the cv2.VideoCapture.read() function incorrectly. The function returns a tuple (ret_val, frame). You are saving that tuple as the frame variable. You are getting an error because you are trying to splice that tuple. You can confirm this by using print(type(frame)).

    If you change the line to ret_val, frame = vs.read() the function works as you intend and the image is correctly spliced