android中YUV转RGB的方法

在一个外国网站上看到一段YUV转RGB的程序很不错,根据维基上的知识,方法应该是没问题的,自己也用过了,效果没问题。

首先说一下android上preview中每一帧的信息都是YUV420的,或者叫NV21,又或者叫YCbCr_420_SP (NV21),反正这么个东西呢,Y,U,V三个分量的数量比是4:1:1.也就是说每四个像素共用一对UV。举个例子,如果是一个30*40的帧,那么有1200个Y分量,分别有300个U和300个V分量。总共有1200*1.5这么多个值。如果调用android中的onPreviewFrame(byte[] data, Camera camera)这个方法,data就是这一帧的数据。数据是这么排列的:

首先是Y分量(亮度)

Y....

Y....

接着是v,u分量成对出现

(v,u),(v,u)......

(v,u),(v,u)......

然后讲一下共用的v,u问题

比如图像是4*4的:

Y11,Y12,Y13,Y14

Y21,Y22,Y23,Y24

Y31,Y32,Y33,Y34

Y41,Y42,Y43,Y44

V,U分量是这样的:

(V1,U1),(V2,U2)

(V3,U3),(V4,U4)

其中,

Y11,Y12,

Y21,Y22,

共用

(V1,U1)

 

Y13,Y14

Y23,Y24

共用

(V2,U2)

其他的同理。

根据以上的介绍,我们就可以写程序了,程序如下:

    int yy,v,u;   //三个分量
    int frame_size=width*height;
    int p_y=x*width+y; //当前像素点y分量的位置
    int p_v=frame_size+(x >> 1) * width + (y& ~1) + 0; //当前像素点v分量的位置
    int p_u=frame_size+(x >> 1) * width + (y& ~1) + 1; //当前像素点u分量的位置
    yy=pSrc[p_y];
    v=pSrc[p_v];
    u=pSrc[p_u];
    yy = yy-16>0 ? yy-16 : 0; 
    v= v-128>0?v-128:0;
    u=u-128>0?u-128:0; //开始转化成rgb
    unsigned char r = (unsigned char) ((116 *(int)yy + 160 *(int)v)/100);
    unsigned char g = (unsigned char) ((116 * (int)yy - 81 * (int)v - 39 * (int)u)/100);
    unsigned char b = (unsigned char) ((116 * (int)yy + 202 * (int)u)/100);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android ,使用 Camera API 获取的图像数据通常是以 YUV 格式传输的。要将 YUV 数据换为 RGB,可以使用以下方法: 1. 使用 Android 提供的 YUV 换工具类:YuvImage 和 BitmapFactory。这种方法的缺点是比较耗时,而且需要将 YUV 数据先换为 JPEG 或 PNG 格式,然后再换为 RGB。代码示例: ``` YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, width, height, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); yuvImage.compressToJpeg(new Rect(0, 0, width, height), 50, out); byte[] imageBytes = out.toByteArray(); Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); ``` 2. 使用 RenderScript 进行 YUV 换。RenderScript 是 Android 提供的高性能计算引擎,可以在 GPU 上进行并行计算,比 CPU 要快很多。代码示例: ``` RenderScript rs = RenderScript.create(context); ScriptIntrinsicYuvToRGB yuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs)); Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs)).setX(data.length); Allocation in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT); in.copyFrom(data); Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height); Allocation out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT); yuvToRgb.setInput(in); yuvToRgb.forEach(out); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); out.copyTo(bitmap); rs.destroy(); ``` 注意:以上代码示例的参数 data 是 byte[] 类型的 YUV 数据,width 和 height 分别是图像宽度和高度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值