Recently, I've been playing around with images taken from videos with the combination of "ffmpeg + python + opencv". This time, I will try to use these to "convert color videos to black and white".
OS: Windows7(Cygwin) ffmpeg: N-74313-g9c0407e Python: 2.7.10 OpenCV: 2.4.11
Create a working folder and place the original video file.
$ mkdir bwmovie/row bwmovie/bw
$ mv movie bwmovie/
$ cd bwmovie
Move to the working folder and use ffmpeg to extract still images frame by frame from the video file.
$ ffmpeg -i movie -f image2 row/%06d.jpg
The last argument is the file name. In this case, the file name is given in the row folder so that it is "arranged in order from the one extracted with a 6-digit integer packed with 0s".
This conversion is done in Python + OpenCV. Create the following python code directly under the working folder.
import cv2
import glob
paths = glob.glob('row/*')
for index,path in enumerate(paths):
image = cv2.imread(path, 0)
ret, th = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU )
cv2.imwrite('bw/%06d.jpg' % index, th)
What this code is doing is first get the files under the row folder as an array with paths = glob.glob ('row / *')
.
Then turn these file paths in a for loop and store them in image with ʻimage = cv2.imread (path, 0). At this time, 0 is specified for the second argument of imread so that it becomes grayscale. After that, binarize (black and white) the image with
ret, th = cv2.threshold (image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) and
cv2.imwrite ('bw /% 06d.jpg) Save it as a serial number in the image bw folder with'% index, th) `.
Finally, join the images converted to black and white to make a video.
ffmpeg -i bw/%06d.jpg video.mp4
Specify the original image after the i option, and specify the output file name in the last argument.
With the above, you can "convert the video to black and white". However, the video output by this method has no audio and the bit rate is not specified, so the number of frames will increase compared to the original video and it will be a little dull. If you are a Kininal, please try google with "How to use ffmpeg".
Recommended Posts