Files
fbclock/lib/image/rgb565.py
T
2026-07-09 14:15:38 +03:00

24 lines
988 B
Python

import numpy as np
from PIL import Image, ImageDraw, ImageFont
def convert_rgb_to_rgb565_numpy(image):
if image.mode != 'RGB':
raise ValueError('Image must be in RGB mode')
# Convert image to NumPy array
img_array = np.array(image)
# Extract the individual RGB components
r = img_array[:,:,0].astype(np.uint16)
g = img_array[:,:,1].astype(np.uint16)
b = img_array[:,:,2].astype(np.uint16)
# Shift the bits into the correct positions for RGB565
# rgb565_array = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
# Shift the bits into the correct positions for RGB565 using NumPy's bitwise functions
rgb565_array = np.bitwise_or(np.bitwise_or(np.left_shift(np.bitwise_and(r, 0xF8), 8),
np.left_shift(np.bitwise_and(g, 0xFC), 3)),
np.right_shift(b, 3))
# Flatten the array to a 1D array of bytes and return
return rgb565_array.flatten().tobytes()