python - OpenCV在Python中将RGB数组转换为YUV422

标签 python opencv

我需要将 RGB uint8 720x480x3 numpy 数组转换为 YUV422 uint8 720x480x2 数组。如何使用 OpenCV 做到这一点?如果 OpenCV 不支持它,是否有另一个 Python 框架会支持它?

最佳答案

OpenCV 不支持您在评论中发布的 RGB 到 YUV 转换公式。

您可以使用 NumPy “手动”实现转换:

  • 将 RGB (BGR) 拆分为 R、G 和 B 并转换为 float .
  • 根据 here 描述的公式计算 Y、U、V .
  • 水平向下采样 U 和 V(水平调整一半)。
  • 圆形,剪辑到 uint8 的范围并转换为 np.uint8类型。
  • 交错 U 和 V channel 。
  • 合并 U 和 UV channel 。

  • 这是一个代码示例:
    import numpy as np
    import cv2
    
    # Prepare BGR input (OpenCV uses BGR color ordering and not RGB):
    bgr = cv2.imread('chelsea.png')
    bgr = cv2.resize(bgr, (150, 100)) # Resize to even number of columns
    
    # Split channles, and convert to float
    b, g, r = cv2.split(bgr.astype(float))
    
    rows, cols = r.shape
    
    # Compute Y, U, V according to the formula described here:
    # https://developer.apple.com/documentation/accelerate/conversion/understanding_ypcbcr_image_formats
    # U applies Cb, and V applies Cr
    
    # Use BT.709 standard "full range" conversion formula
    y = 0.2126*r + 0.7152*g + 0.0722*b
    u = 0.5389*(b-y) + 128
    v = 0.6350*(r-y) + 128
    
    # Downsample u horizontally
    u = cv2.resize(u, (cols//2, rows), interpolation=cv2.INTER_LINEAR)
    
    # Downsample v horizontally
    v = cv2.resize(v, (cols//2, rows), interpolation=cv2.INTER_LINEAR)
    
    # Convert y to uint8 with rounding:
    y = np.round(y).astype(np.uint8)
    
    # Convert u and v to uint8 with clipping and rounding:
    u = np.round(np.clip(u, 0, 255)).astype(np.uint8)
    v = np.round(np.clip(v, 0, 255)).astype(np.uint8)
    
    # Interleave u and v:
    uv = np.zeros_like(y)
    uv[:, 0::2] = u
    uv[:, 1::2] = v
    
    # Merge y and uv channels
    yuv422 = cv2.merge((y, uv))
    

    关于python - OpenCV在Python中将RGB数组转换为YUV422,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60889484/

    相关文章:

    python - 散列时间字符串 : Why not receive same results?

    opencv - Eigenfaces人脸识别训练数据

    c++ - OpenCV 3.4:CPU和CUDA中调整大小的结果在C++中不匹配

    Python:HTMLParser 如何处理来自子标签的数据

    python - 如何将文件夹从 AzureML 笔记本文件夹下载到本地或 Blob 存储?

    python - 从 Python 字典中的列表中提取字符串

    python - 用漂亮的汤和 Pandas 刮 table 时如何保留链接

    c++ - 访问负像素值 OpenCV

    java - 在 HoughCircles(), OpenCV 给出的一系列点上使用 warpPerspective()

    OpenCV:从所有像素中减去相同的 BGR 值