C语言实现YUV420图像90度旋转
以下是用C语言实现YUV420图像旋转90度的示例代码:
#include <stdio.h>
#include <stdlib.h>
void rotate_yuv420(unsigned char *src, unsigned char *dst, int width, int height)
{
int i, j, k;
int y, u, v;
int src_idx, dst_idx;
unsigned char *src_y = src;
unsigned char *src_u = src + width * height;
unsigned char *src_v = src + width * height + width * height / 4;
unsigned char *dst_y = dst;
unsigned char *dst_u = dst + width * height;
unsigned char *dst_v = dst + width * height + width * height / 4;
// rotate Y
for (i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
src_idx = j * width + i;
dst_idx = (width - i - 1) * height + j;
*(dst_y + dst_idx) = *(src_y + src_idx);
}
}
// rotate U and V
for (k = 0; k < 2; k++) {
for (i = 0; i < width / 2; i++) {
for (j = 0; j < height / 2; j++) {
src_idx = j * width / 2 + i;
dst_idx = (width / 2 - i - 1) * height / 2 + j;
if (k == 0) {
*(dst_u + dst_idx) = *(src_u + src_idx);
} else {
*(dst_v + dst_idx) = *(src_v + src_idx);
}
}
}
}
}
int main()
{
int width = 640;
int height = 480;
int size = width * height * 3 / 2;
unsigned char *src = (unsigned char *)malloc(size);
unsigned char *dst = (unsigned char *)malloc(size);
// fill src with some random data
for (int i = 0; i < size; i++) {
*(src + i) = i % 255;
}
// rotate src and save to dst
rotate_yuv420(src, dst, width, height);
// print some data for verification
printf("src[0] = %d, dst[%d] = %d\n", *(src), width * height * 5 / 4, *(dst + width * height * 5 / 4));
printf("src[%d] = %d, dst[%d] = %d\n", width * height - 1, *(src + width * height - 1), width * height / 2, *(dst + width * height / 2));
printf("src[%d] = %d, dst[%d] = %d\n", width * height + width * height / 4 - 1, *(src + width * height + width * height / 4 - 1), width * height + width * height / 4, *(dst + width * height + width * height / 4));
free(src);
free(dst);
return 0;
}
此代码假设输入的图像为YUV420格式,其中Y分量占据前width * height个字节,U分量占据接下来的width * height / 4个字节,V分量占据接下来的width * height / 4个字节。输出的图像也是YUV420格式。该函数会将输入图像顺时针旋转90度,然后保存到输出图像中。
原文地址: https://www.cveoy.top/t/topic/lC9I 著作权归作者所有。请勿转载和采集!