Home > OS >  Frames not written in output video after cv2.inRange is used
Frames not written in output video after cv2.inRange is used

Time:03-16

I'm trying to perform object detection (in a video I recorded) through thresholding in BGR color space and save the result in an output video.

The preview I get using cv2.imshow is correct, the binary map I get for the object location is the right one. However, these frames showing the binary map (the ones I process using cv2.inRange() ) are missing from the output video. The rest of the video frames are properly written in the output video. Does anyone know what could be causing this issue? Thanks!

This is my code:


import cv2

# helper function to change what you do based on video seconds
# arguments "lower: int" and "upper: int" are measured in milliseconds
def between(cap, lower: int, upper: int) -> bool:
    return lower <= int(cap.get(cv2.CAP_PROP_POS_MSEC)) < upper

cap = cv2.VideoCapture(input_video_file_path)
fps = int(round(cap.get(5)))
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')        # saving output video as .mp4
out = cv2.VideoWriter(output_video_file_path, fourcc, fps, (frame_width, frame_height)) # to create a VideoWriter object

# while loop where the real work happens
while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        if cv2.waitKey(28) & 0xFF == ord('q'):
            break

        if between(cap, 1000, 4000):                        
            lower_blue = (82,0,0) #BGR
            upper_blue = (255,143,61)
            frame = cv2.inRange(frame,lower_blue,upper_blue)
            frame = cv2.putText(frame, 'Grab in RBG', (50,50),cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255,255,255), 2, cv2.LINE_AA)  
        
        # write frame that you processed to output
        out.write(frame)

        # (optional) display the resulting frame
        cv2.imshow('Frame', frame)

        # Press Q on keyboard to  exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break

    # Break the loop
    else:
        break

# When everything done, release the video capture and writing object
cap.release()
out.release()
# Closes all the frames
cv2.destroyAllWindows()

CodePudding user response:

you opened the VideoWriter in color mode (isColor=True) but the result from inRange() has only a single channel, so it wont get written to the video. add a

cv2.cvtColor(frame,frame,cv2.COLOR_GRAY2BGR)

after the inRange(), so the frame you try to write has the nessecary number of channels

  • Related