ppcrong
ppcrong

Reputation: 218

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. 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:

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

I don't see any convert code about cv2.COLOR_BGR2RGB565, is there any other function to support RGB888 to RGB565?

Or someone knows how to convert ndarray RGB888 to RGB565?

Upvotes: 2

Views: 4931

Answers (2)

Stéphane
Stéphane

Reputation: 20360

Why not use the usual cvtColor() function from OpenCV? I see enums such as COLOR_BGR2BGR565, COLOR_BGR5652BGR, COLOR_BGR5652RGB, and COLOR_RGBA2BGR565 among others. Wouldn't it be better to use OpenCV to do the conversion vs writing your own?

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207668

I think this is right but don't have anything RGB565 to test it on:

#!/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:

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

Upvotes: 2

Related Questions