Reputation: 23
im new to python and i want to turn a color video to grayscale and then save it. Ive tried this code to make it grayscale but i cant save it. Any ideas?
import cv2
source = cv2.VideoCapture('video.mp4')
while True:
ret, img = source.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Live', gray)
key = cv2.waitKey(1)
if key == ord('q'):
break
cv2.destroyAllWindows()
source.release()
Upvotes: 1
Views: 5309
Reputation: 3260
Here is a shorter way of doing this using ImageIO. The example use one of our standard images, so you can run it locally, too.
import imageio.v3 as iio
with iio.imopen("output_video.mp4", "w") as file:
file.init_video_stream("libx264", fps=24, pixel_format="gray")
for frame in iio.imread("imageio:cockatoo.mp4"):
file.write_frame(frame)
Note that you will have to install its pyav backend (pip install imageio[pyav]
) for this to work.
Upvotes: 1
Reputation:
This is the way how to write an RGB video file into the grayscale video
# importing the module
import cv2
import numpy as np
# reading the vedio
source = cv2.VideoCapture('input.avi')
# We need to set resolutions.
# so, convert them from float to integer.
frame_width = int(source.get(3))
frame_height = int(source.get(4))
size = (frame_width, frame_height)
result = cv2.VideoWriter('gray.avi',
cv2.VideoWriter_fourcc(*'MJPG'),
10, size, 0)
# running the loop
while True:
# extracting the frames
ret, img = source.read()
# converting to gray-scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# write to gray-scale
result.write(gray)
# displaying the video
cv2.imshow("Live", gray)
# exiting the loop
key = cv2.waitKey(1)
if key == ord("q"):
break
# closing the window
cv2.destroyAllWindows()
source.release()
If helpful this for you give 👍
Upvotes: 2