I try to record a video in python. Running the code below create me a .mp4 file but is is 0KB and when i open i get the error that the data is corrupted and unable to open. I tried opening with VLC, Media Player and all other toold i got on Windows 11. Also tried everything available on the internet same problem every time
import cv2
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1280)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 720)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
writer = cv2.VideoWriter('recording.mp4', fourcc, 30.0, (1280, 720))
recording = False
while True:
ret, frame = cap.read()
if ret:
print('working')
cv2.imshow("video", frame)
if recording:
writer.write(frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
elif key == ord('r'):
recording = not recording
print(f'recording: {recording}')
# Release the video capture and writer objects
cap.release()
writer.release()
cv2.destroyAllWindows()
You are setting a size manually, but the camera might not work at that resolution.
To solve the problem, you can manually set the resolution to 1280x720 but then instead of hardcoding the capture resultion, retrieve it from the camera
This way if the camera works at the desired resolution good, if not it will work at the default one.