简体   繁体   English

如何在 python 中使用 opencv-python 将 RGB888 转换为 RGB565?

[英]How can I use opencv-python to convert RGB888 to RGB565 in python?

I would like to read camera image by opencv-python and send image raw data (byte array) in RGB565 format to device.我想通过opencv-python读取相机图像并将 RGB565 格式的图像原始数据(字节数组)发送到设备。 Here are some testing codes:下面是一些测试代码:

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

After codes run, it returned "show" ndarray (numpy) by cvtColor at last line, the "show" ndarray info is:代码运行后,它在最后一行通过 cvtColor 返回“show” ndarray (numpy), “show” ndarray 信息为:

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

I don't see any convert code about cv2.COLOR_BGR2RGB 565 , is there any other function to support RGB888 to RGB565?我没有看到任何关于 cv2.COLOR_BGR2RGB 565的转换代码,是否还有其他 function 支持 RGB888 到 RGB565?

Or someone knows how to convert ndarray RGB888 to RGB565?或者有人知道如何将ndarray RGB888 转换为 RGB565?

I think this is right but don't have anything RGB565 to test it on:我认为这是正确的,但没有任何 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)

Or, you can remove your cv2.cvtColor(show, cv2.COLOR_BGR2RGB) and swap the indices to:或者,您可以删除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)  

Why not use the usual cvtColor() function from OpenCV?为什么不使用 OpenCV 中的常用cvtColor() function? I see enums such as COLOR_BGR2BGR565 , COLOR_BGR5652BGR , COLOR_BGR5652RGB , and COLOR_RGBA2BGR565 among others.我看到了诸如COLOR_BGR2BGR565COLOR_BGR5652BGRCOLOR_BGR5652RGBCOLOR_RGBA2BGR565等枚举。 Wouldn't it be better to use OpenCV to do the conversion vs writing your own?使用 OpenCV 进行转换与自己编写不是更好吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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