没有从 RGB 到 YUV 的转换

No conversion from RGB to YUV

我无法在任何 Python 库(最好是 PIL)中找到用于从 RGB 转换为 YUV 的易于使用的函数。 由于我要转换很多图像,我不想自己实现它(如果没有 LUT 等会很昂贵)。

当我做直觉的时候:

from PIL import Image
img = Image.open('test.jpeg')
img_yuv = img.convert('YUV')

我收到一个错误:

ValueError: conversion from RGB to YUV not supported

你知道为什么会这样吗? 在 python 甚至 PIL 中是否有任何有效的实现?

我不是计算机视觉专家,但我认为这个 ocnversion 在大多数库中都是标准的...

谢谢,

罗马

你可以试试这个:

import cv2
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)

您可以尝试 'YCbCr' 而不是 'YUV',即

from PIL import Image
img = Image.open('test.jpeg')
img_yuv = img.convert('YCbCr')

我知道可能晚了,但是scikit-image有函数rgb2yuv

from PIL import Image
from skimage.color import rgb2yuv

img = Image.open('test.jpeg')
img_yuv = rgb2yuv(img)    

如果你不想安装任何额外的包,你可以看看skimage source code。以下片段摘自该 github 页面,并进行了一些小改动:

# Conversion matrix from rgb to yuv, transpose matrix is used to convert from yuv to rgb
yuv_from_rgb = np.array([[ 0.299     ,  0.587     ,  0.114      ],
                     [-0.14714119, -0.28886916,  0.43601035 ],
                     [ 0.61497538, -0.51496512, -0.10001026 ]])

# Optional. The next two line can be ignored if the image is already in normalized numpy array.
# convert image array to numpy array and normalize it from 0-255 to 0-1 range
new_img = np.asanyarray(your_img)
new_img = dtype.img_as_float(new_img)

# do conversion
yuv_img = new_img.dot(yuv_from_rgb.T.copy())