【问题标题】:How can I use opencv-python to convert RGB888 to RGB565 in python?如何在 python 中使用 opencv-python 将 RGB888 转换为 RGB565?
【发布时间】:2023-11-24 02:36:01
【问题描述】:

我想通过 opencv-python 读取相机图像并将 RGB565 格式的图像原始数据(字节数组)发送到设备。 下面是一些测试代码:

import cv2
cam = cv2.VideoCapture(0) # open camera
flag, image = cam.read() # read image from camera
show = cv2.resize(image, (640, 480)) # resize to 640x480
show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB) # convert to RGB888

代码运行后,最后一行返回"show" ndarray (numpy) by cvtColor,"show" ndarray信息为:

>>> show.shape
(480, 640, 3)
>>> show.dtype
dtype('uint8')
>>> show.size
921600

我没有看到任何关于cv2.COLOR_BGR2RGB565的转换代码,还有其他支持RGB888到RGB565的函数吗?

或者有人知道如何将 ndarray RGB888 转换为 RGB565?

【问题讨论】:

    标签: python-3.x numpy rgb opencv-python


    【解决方案1】:

    我认为这是正确的,但没有任何 RGB565 可供测试:

    #!/usr/bin/env python3
    
    import numpy as np
    
    # Get some deterministic randomness and synthesize small image
    np.random.seed(42)
    im = np.random.randint(0,256,(1,4,3), dtype=np.uint8)
    
    # In [67]: im
    # Out[67]:
    # array([[[102, 220, 225],
    #        [ 95, 179,  61],
    #        [234, 203,  92],
    #        [  3,  98, 243]]], dtype=uint8)
    
    # Make components of RGB565
    R5 = (im[...,0]>>3).astype(np.uint16) << 11
    G6 = (im[...,1]>>2).astype(np.uint16) << 5
    B5 = (im[...,2]>>3).astype(np.uint16)
    
    # Assemble components into RGB565 uint16 image
    RGB565 = R5 | G6 | B5
    
    # Produces this:
    # array([[26364, 23943, 61003,   798]], dtype=uint16)
    

    或者,您可以删除您的 cv2.cvtColor(show, cv2.COLOR_BGR2RGB) 并将索引交换为:

    R5 = (im[...,2]>>3).astype(np.uint16) << 11
    G6 = (im[...,1]>>2).astype(np.uint16) << 5
    B5 = (im[...,0]>>3).astype(np.uint16)  
    

    【讨论】:

    • 顺便问一下马克,请问我下面的代码是否正确将RGB565传输到字节数组? raw = RGB565.tobytes()
    • 谢谢马克,我刚接触python,可能会经常问一些基本问题。 ^^
    • 没关系...我们都是来学习的。问题是免费的,和答案一样! :-)
    • 嗨,马克,我有类似的问题,关于 RGB565 到 RGB888 的测试代码,但我卡住了......XD,如果你有时间,请帮助我。 ^^ 请参考*.com/questions/61816430/…
    最近更新 更多