Conversion from YUV420sp to RGB in python

688 views Asked by At

I am making an Android app that sends images of the preview screen over internet. bytes of the YUV image are sent. I want to convert this YUV NV21 image to RGB colorspace. I looked at conversion function in this link http://www.41post.com/3470/programming/android-retrieving-the-camera-preview-as-a-pixel-array . And wrote a python code doing samethinng. Here is the python code.

import numpy as np
from struct import unpack

def nv21torgb(byarray,width,height):
    img = np.ndarray(shape=(height,width,3),dtype=np.uint8)
    xra = range(height)
    yra = range(width)
    frameSize = width*height
    yp = 0
    for j in xra:
        uvp = frameSize + (j >> 1)*width
        u = 0
        v = 0
        for i in yra:
            y = unpack('B',byarray[yp])[0] - 16
            if i & 1 is 0:
                v = unpack('B',byarray[uvp])[0] - 128
                uvp = uvp + 1
                u = unpack('B',byarray[uvp])[0] - 128
                uvp = uvp + 1
            y1192 = 1192 * y
            r = y1192 + 1634*v
            g = y1192 - 833*v - 400*u
            b = y1192 + 2066*u
            if r<0:
                r = 0
            elif r>262143:
                r = 262143
            if g < 0:
                g = 0
            elif g>262143:
                g = 262143
            if b<0:
                b = 0
            elif b>262143:
                b = 262143
            r = ((r<<6)&0xff0000)>>16
            g = ((g>>2)&0xff00)>>8
            b = ((b>>10)&0xff)
            img[j][i] = [r,g,b]
    return img

But this function seems wrong somewhere because i am getting weird output. image

Thanks for helping :)

1

There are 1 answers

0
greeble31 On

I think you forgot to increment yp with each iteration. Refer to line 88 of the code you linked.