简体   繁体   中英

How can I read YUV in opencv with python?

I read picture using "cv.imread"

What I wanted to do was "comparing from 'convert to yuv from rgb with fomula' to 'convert to yuv from rgb using cv.cvtColor(img, cv.COLOR_BGR2YUV)'

and this is my code

img = cv.imread('pic.jpeg')

# convert to yuv using fomula
toYUV = np.zeros((len(img), len(img[0]), 3), np.uint8)
for i in range(len(img)):
    for j in range(len(img[0])):
        y = 0.257*img[i][j][0] + 0.504*img[i][j][1]+0.095*img[i][j][2]+16
        u = -0.148*img[i][j][0] - 0.291*img[i][j][1]+0.499*img[i][j][2]+128
        v = 0.439*img[i][j][0] - 0.368*img[i][j][1]-0.071*img[i][j][2]+128
        toYUV[i][j] = [y, u, v]
cv.imshow('toYUV', toYUV)

# convert to yuv using cvtColor
yuv = cv.cvtColor(img, cv.COLOR_BGR2YUV)

cv.imshow('yuv', yuv)

as you see, I saved converted value using fomula, but the result was not that I expected.

I think I saved YUV format data to toYUV, but cv.imshow read it just like RGB format How I read my "toYUV" that contains YUV data?

If you use PIL/Pillow , ImageMagick or wand , they have an image "container" that keeps track of the type of your image and any metadata, such as EXIF or IPTC and ICC colour profiles. So, if you open an image with PIL and convert it to HSV colourspace, PIL knows and remembers that your pixel values now represent Hue, Saturation and Value rather than RGB.

OpenCV doesn't do that - it is more interested in hard-core, high performance computer vision (hence the name) than cataloguing, indexing and managing photo archives. It stores your pixels in a very simple Numpy array and other than the dimensions of the array, has no understanding or interest in what the pixels mean - it generally assumes they are BGR when saving and displaying them - or maybe greyscale or BGRA if there are 1 or 4 channels.


Coming back closer to your question, I think you'll find it easier to treat your YUV image as three independent greyscale images if you want to compare them. So you could use Y,U,V = cv2.split(YOURIMAGE) to split your Y, U and V channels into 3 separate, single-channel images, then use rowOfThree = np.hstack((Y,U,V)) to put the three grey channels side-by-side in a row for display.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM