Rajesh Gopu
Rajesh Gopu

Reputation: 893

How to convert raw Y video buffer to image using python?

I have a raw file of Y video plane (y.raw) extracted from raw video frame format YUV (YUV422_SEMI_PLANAR).How to convert this y.raw as image png or jpg ?

Upvotes: 1

Views: 1325

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 208043

You have essentially got a single channel greyscale image with no packing or interleaving. So you have a few options:

  • ImageMagick at the command line,
  • via NetPBM PGM format and Photoshop, or GIMP
  • Python

ImageMagick at command line in Terminal

If you have ImageMagick installed like most Linux distros already do (or you can install it for free on Mac and Windows) you could convert it to like this in Terminal.

Say it is 640x480 pixels and 8-bit and you want a PNG:

convert -depth 8 -size 640x480 gray:y.raw result.png

Say it is 1024x768 pixels and 16 bit and you want a contrast-stretched JPG:

convert -depth 16 -size 1024x768 gray:y.raw -auto-level result.jpg

Via NetPBM PGM format and Photoshop or GIMP

Say you don't have ImageMagick, you could make the file into a NetPBM PGM (Portable Grey Map) that you can view/edit/save in GIMP, Paint, feh, Adobe Photoshop:

{ printf "P5\n640 480\n255\n"; cat y.raw; } > result.pgm

If you are unfortunate enough to be on Windows and want to do it this way, I think it would look something like this:

echo "P5"        > header.txt
echo "640 480"  >> header.txt
echo "255"      >> header.txt
copy /b header.txt+y.raw result.ppm

Python

If you really, really want to write a bunch of Python, it might look like this:

#!/usr/local/bin/python3

from PIL import Image

file=open("y.raw",'rb')
rawdata=file.read()
file.close()

imgsize = (640,480)

# Use the PIL raw decoder
img = Image.frombytes('L',imgsize,rawdata)
img.save('result.png')

If anyone else is reading this and wishes they had a frame of Y data to play around with, you can easily create a simulated one containing a black-white gradient with ImageMagick like this:

convert -size 640x480 gradient: -depth 8 gray:y.raw

enter image description here

That will look like this with ls:

-rw-r--r--   1 mark  staff  307200 23 Mar 10:05 y.raw

Upvotes: 4

Related Questions