Tutorial: Converting PNG into YUV Using FFmpeg or OpenCV C++ API

Sik-Ho Tsang
2 min readMay 12, 2020

--

FFmpeg & OpenCV

In this short story, I just want to mark down the way to convert PNG into YUV either using FFmpeg, or OpenCV C++ API. Of course, there are many ways to do it. (Sik-Ho Tsang @ Medium)

1. FFmpeg

1.1. Download FFmpeg

1.2. Convert PNG into YUV

  • To convert a PNG file into YUV, just simply enter below command with pixel format specified as YUV420:
ffmpeg -i 0001.png -pix_fmt yuv420p 0001.yuv
  • Then we can convert 0001.png into 0001.yuv.

2. OpenCV C++ API

  • As I need some manipulations during the conversion, so I also tried OpenCV C++ API.

2.1. OpenCV C++ API Installation

2.2. Convert PNG into YUV

  • First, include some headers:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
  • Then, in the main function, to read the 0001.png, and also get the width and height of the image:
Mat image =  imread("0001.png");
int iHeight = image.size[0];
int iWidth = image.size[1];
  • And convert image into yuv by specifying COLOR_BGR2YUV_I420:
Mat yuv;
cvtColor(image, yuv, COLOR_BGR2YUV_I420);
  • Finally, estimate the buffer size for YUV420, write out the YUV buffer to file as 0001.yuv:
int bufLen = iWidth * iHeight * 3 / 2;
unsigned char* pYuvBuf = new unsigned char[bufLen];
File * pFileYuv;
fopen_s(&pFileYuv, "0001.yuv", "wb");
fwrite(yuv.data, sizeof(unsigned char), bufLen, pFileYuv);fclose(pFileYuv);
pFileYuv = NULL;
delete [] pYuvBuf;

During the days of coronavirus, let me have a challenge of writing 30 stories again for this month ..? Is it good? This is the 17th story in this month. Thanks for visiting my story..

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sik-Ho Tsang
Sik-Ho Tsang

Written by Sik-Ho Tsang

PhD, Researcher. I share what I learn. :) Linktree: https://linktr.ee/shtsang for Twitter, LinkedIn, etc.

Responses (1)

Write a response