Skip to content

Instantly share code, notes, and snippets.

@dmitriykovalev
Last active August 14, 2025 13:13
Show Gist options
  • Select an option

  • Save dmitriykovalev/980f4bcf68ac4667e89d4d989de21835 to your computer and use it in GitHub Desktop.

Select an option

Save dmitriykovalev/980f4bcf68ac4667e89d4d989de21835 to your computer and use it in GitHub Desktop.
Convert NV12 YUV image to RGB image using Python
import argparse
from PIL import Image
def nv12_to_rgb(nv12: bytes | bytearray, size: tuple[int, int]) -> Image:
w, h = size
n = w * h
y, u, v = nv12[:n], nv12[n + 0::2], nv12[n + 1::2]
yuv = bytearray(3 * n)
yuv[0::3] = y
yuv[1::3] = Image.frombytes('L', (w // 2, h // 2), u).resize(size).tobytes()
yuv[2::3] = Image.frombytes('L', (w // 2, h // 2), v).resize(size).tobytes()
return Image.frombuffer('YCbCr', size, yuv).convert('RGB')
if __name__ == '__main__':
def size(s):
w, sep, h = s.partition('x')
if sep != 'x':
raise ValueError()
return int(w), int(h)
parser = argparse.ArgumentParser()
parser.add_argument('-s', type=size, metavar='WxH', required=True)
parser.add_argument('input')
parser.add_argument('output')
args = parser.parse_args()
nv12_to_rgb(open(args.input, 'rb').read(), args.s).save(args.output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment