Python_yuv读取,yuv转rgb

# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 10:48:00 2013

@author: Chen Ming
"""

from numpy import *
import Image 
screenLevels = 255.0

         
def yuv_import(filename,dims,numfrm,startfrm):
    fp=open(filename,'rb')
    blk_size = prod(dims) *3/2
    fp.seek(blk_size*startfrm,0)
    Y=[]
    U=[]
    V=[]
    print dims[0]
    print dims[1]
    d00=dims[0]//2
    d01=dims[1]//2

    Yt=zeros((dims[0],dims[1]),uint8,'C')
    Ut=zeros((d00,d01),uint8,'C')
    Vt=zeros((d00,d01),uint8,'C')
    for i in range(numfrm):
        for m in range(dims[0]):
            for n in range(dims[1]):
                #print m,n
                Yt[m,n]=ord(fp.read(1))
        for m in range(d00):
            for n in range(d01):
                Ut[m,n]=ord(fp.read(1))
        for m in range(d00):
            for n in range(d01):
                Vt[m,n]=ord(fp.read(1))
        Y=Y+[Yt]
        U=U+[Ut]
        V=V+[Vt]
    fp.close()
    return (Y,U,V)
    
def yuv2rgb(Y,U,V,width,height):
    U=repeat(U,2,0)
    U=repeat(U,2,1)
    V=repeat(V,2,0)
    V=repeat(V,2,1)
    r=zeros((480,640),float,'C')
    g=zeros((480,640),float,'C')
    b=zeros((480,640),float,'C')
    rr=zeros((480,640),float,'C')
    gg=zeros((480,640),float,'C')
    bb=zeros((480,640),float,'C')
    rr= Y+1.14*(V-128.0)
    gg= Y-0.395*(U-128.0)-0.581*(V-128.0)
    bb= Y+2.032*(U-128.0)             # 必须是128.0,否则出错

    rr1=rr.astype(uint8)
    gg1=gg.astype(uint8)
    bb1=bb.astype(uint8)

    print 'rr1:'
    print rr1[0:3,0:30]
    
    return rr1,gg1,bb1
    
   

if __name__ == '__main__':
    data=yuv_import('E:\\new\\test\\ballroom\\ballroom_0.yuv',(480,640),1,0)

    YY=data[0][0]
    print YY.shape

    im=Image.fromstring('L',(640,480),YY.tostring())
    im.save('f:\\a.jpg')
    R_=data[0][0]
    G_=data[1][0]
    B_=data[2][0]
    RGB=yuv2rgb(R_,G_,B_,640,480)
    im_r=Image.fromstring('L',(640,480),RGB[0].tostring())
    im_g=Image.fromstring('L',(640,480),RGB[1].tostring())
    im_b=Image.fromstring('L',(640,480),RGB[2].tostring())
    im_r.show()
    for m in range(2):
        print m,': ', R_[m,:]
    co=Image.merge('RGB', (im_r,im_g,im_b))
    co.show()
    co.save('F:\\haha.jpg')


 

array的类型强制转化:

a=zeros((2,2),float)  # 浮点

b=a.astype(uint8)   # 转为uint8,将小数去掉

 

计算时的隐式转化:

a=array(....,uint8)

a*1.0   # 变为浮点

上述代码中:

rr= Y+1.14*(V-128.0)

gg= Y-0.395*(U-128.0)-0.581*(V-128.0)

 bb= Y+2.032*(U-128.0) # 必须是128.0,否则出错

 

如果使用“-128”的形式,那么“U-128”或“V-128”本来应该可能得到负的整数(如30-128),

但由于U、V是uint8型的,所以会被变成(256+30-128),成为一个大的正整数,导致错误。虽然后面又乘以浮点数的运算,

会被自动转为浮点,但这一步已经错了。所以一定要减去128.0,而不是减去128。

效果:

 

 

rr= Y+1.14*(V-128) 时的效果:

 

 

gg= Y-0.395*(U-128)-0.581*(V-128)

的效果:

 

你可能感兴趣的:(Python)