Last active
August 14, 2025 13:13
-
-
Save dmitriykovalev/980f4bcf68ac4667e89d4d989de21835 to your computer and use it in GitHub Desktop.
Convert NV12 YUV image to RGB image using Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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