Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode grayscale video streams to MPEG-1 with FFmpeg?

I've got a grayscale video stream coming off a Firewire astronomy camera, I'd like to use FFmpeg to compress the video stream but it will not accept single byte pixel formats for the MPEG1VIDEO codecs. How can I use the FFmpeg API to convert grayscale video frames into a frame format accepted by FFmpeg?

like image 236
Gearoid Murphy Avatar asked Dec 01 '11 22:12

Gearoid Murphy


2 Answers

MPEG-1 only accepts YUV so you need to convert your frame to the YUV format. Use the SwsContext structure which you create by calling sws_getContext(), and then use sws_scale().

like image 113
sashoalm Avatar answered Oct 20 '22 21:10

sashoalm


The Relationship of Gray scale and YUV is very simple - The "Y" of YUV is exactly same as Grayscale.

The simpler way to convert the Grayscale in to YUV is

See this reference for Conversion between the scales :

Accordingly :

Y  =      (0.257 * R) + (0.504 * G) + (0.098 * B) + 16
Cr = V =  (0.439 * R) - (0.368 * G) - (0.071 * B) + 128
Cb = U = -(0.148 * R) - (0.291 * G) + (0.439 * B) + 128

Now: 
For a Grayscale image (W): 

R = W;
G = W;
B = W;

Keeping this: 

Y[i] = 0.895 * W[i] + 16. 
U[i] = 128 (fixed value)
V[i] = 128 (fxied value)

You can actually use Y[i] = W[i] that will be almost same. The 128 value represents '0' in a scaled/shifted base of 0-256 signed to unsigned conversion.

So all you need to keep is create this other memory area Y and U as the fixed value and provide this frames to ffmpeg.

I am not sure, but by appropriately telling FFMPEG, it does this inside only. The RGB values you supply are equally covered there as well; which is also not native to MPEG.

So look for FFMPEG's API which is able to let you do this.

BONUS
Remember, that in good old days there were Black and white (Gray scale) TV sets. The new color TV sets, needed to be compliant to the old ones, so color information is added in the form of U and V (sometimes it is also called YCbCr - where Cb and Cr are called chroma and are respectively linear variations of UV in this context).

like image 35
Dipan Mehta Avatar answered Oct 20 '22 21:10

Dipan Mehta