Skip to content

Instantly share code, notes, and snippets.

@iwatake2222
Last active April 11, 2022 03:26
Show Gist options
  • Save iwatake2222/0f27d7faa3759679081ab1e1c2bdc5d0 to your computer and use it in GitHub Desktop.
Save iwatake2222/0f27d7faa3759679081ab1e1c2bdc5d0 to your computer and use it in GitHub Desktop.
OpenCV色フォーマット変換(BGR,YUV420, NV12)
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
void save(const char *filename, const unsigned char * data, int size)
{
FILE *fp = fopen(filename, "wb");
fwrite(data, size, 1, fp);
fclose(fp);
}
void convYUV420toNV12(unsigned char *dst, const unsigned char *src, int width, int height)
{
/* for Y */
memcpy(dst, src, width * height);
dst += width * height;
const unsigned char *srcU = src + width * height;
const unsigned char *srcV = srcU + width * height / 4;
for (int y = 0; y < height / 4; y++) {
for (int x = 0; x < width; x++) {
dst[y * (width * 2) + x * 2 + 0] = srcU[y * width + x];
dst[y * (width * 2) + x * 2 + 1] = srcV[y * width + x];
}
}
}
int main()
{
printf("Hello\n");
/* BGR: 4 x 4
BGRBGRBGRBGR
BGRBGRBGRBGR
BGRBGRBGRBGR
BGRBGRBGRBGR
*/
cv::Mat imageBGR = cv::imread(RESOURCE_DIR"lena.jpg");
int width = imageBGR.cols;
int height = imageBGR.rows;
save("imageBGR.raw", imageBGR.data, width * height * 3);
/* YUV420(planer) 4 x 4
YYYY
YYYY
YYYY
YYYY
UUUU
VVVV
*/
cv::Mat imageYUV;
cv::cvtColor(imageBGR, imageYUV, CV_BGR2YUV_I420);
save("imageYUV.raw", imageYUV.data, width * height * 1.5 * 1);
/* NV12(semi-planer) 4 x 4
YYYY
YYYY
YYYY
YYYY
UVUV
UVUV
*/
unsigned char *imageNV12 = new unsigned char[width * height * 1.5];
convYUV420toNV12(imageNV12, imageYUV.data, width, height);
save("imageNV12.raw", imageNV12, width * height * 1.5 * 1);
delete[] imageNV12;
return 0;
}
/*
http://klabgames.tech.blog.jp.klab.com/archives/1054828175.html
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment