2

Firstly, i am sorry if the question is stupid. I'm beginner with python opencv and image processing.

I created a program in order to read the video as the input and save it into the pgm format.

import cv2
vidcap = cv2.VideoCapture('input_video.mp4')
success,image = vidcap.read()
count = 0
while success:
  cv2.imwrite("frame%d.pgm" % count, image)     # save frame as PGM file      
  success,image = vidcap.read()
  print('Read a new frame: ', success)
  count += 1
vidcap.release()

After running i have the frames which seem not exactly the format of PGM image. The "magic number" is "F6" instead of "F5" of PGM format. As i know the "magic number" of PPM format (it maybe call PGM 'color', a lowest common denominator color image file format) is "F6". I don't understand why i cannot have exactly PGM image in this case. Can someone figure me out this question and give me a solution to have the PGM format frames in output ?

The video (I don't know how to upload video here, so i attack the link). I tested with this video and even with its gray-scale version but the "magic number" is always "F6".

In SO, i found this link that may be similar to my question but it is for C++.

Hitokiri
  • 3,607
  • 1
  • 9
  • 29

1 Answers1

2

Your image will be colour, so you will need to convert to greyscale before you can save it as PGM - meaning "Portable Grey Map":

# Convert to grey
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Write to disk
cv2.imwrite("frame%d.pgm" % count, gray)

By the way, IMHO it is normally a bad idea to repeat code that is doing the same thing in different places - it makes a maintenance nightmare. Rather than this where you do vidcap.read() twice:

success,image = vidcap.read()
...
while success:
  cv2.imwrite("frame%d.pgm" % count, image)      
  success,image = vidcap.read()

consider using this so you only read the video in one place and there is only one place to add/change parameters:

while True:
   success,image = vidcap.read()
   if not success:
       break
   cv2.imwrite("frame%d.pgm" % count, image)
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • 1
    Thanks, but i you should edit `cv2.imwrite("frame%d.pgm" % count, image)` to `cv2.imwrite("frame%d.pgm" % count, gray)` ` ` – Hitokiri Apr 08 '20 at 18:47
  • Before i posted the question, i tested with the greyscale video (i used the online converting to convert the video) because i think my image is color, but it did not work. So what happen when i convert video before saving to the frames ? The video is not greyscale or something esle ? – Hitokiri Apr 08 '20 at 18:52
  • 1
    Try printing the shape of the Numpy array after you acquire it, `printf(image.shape)`. If it is `(Y,X)` it is greyscale. If it is `(Y,X,3)` it is colour. – Mark Setchell Apr 08 '20 at 21:23
  • Thank you so much. It is a nice tip – Hitokiri Apr 08 '20 at 21:32