The output pixel color format for rendering in Blender is RGBA in the linear color space. If we need to save the render in RGB565 format, such a format is used, for example, in some old games, the color values of the pixels must be converted.
For example, let’s take the color value for one pixel from the image data from the compositing Viewer Node.
1 2 3 |
bpy.data.images['Viewer Node'].pixels[0:4] # (0.5, 0.0, 0.0, 1.0) |
First, we need to convert it to the sRGB color space:
1 2 3 |
tuple(linear_to_srgb(col) for col in bpy.data.images['Viewer Node'].pixels[0:4]) # (188, 0, 0, 255) |
Having received a color value in the generally used 2D color space, we can now convert it to the format we need.
Let’s define a function to convert color from the RGBA format to the RGB565 format:
1 2 3 4 5 6 7 8 9 10 |
def rgba_rgb565(rgba): r, g, b, a = rgba r = r >> 3 g = g >> 2 b = b >> 3 rgb565 = 0x0000 rgb565 |= ((r & 0x1F) << 11) rgb565 |= ((g & 0x3F) << 5) rgb565 |= (b & 0x1F) return rgb565 |
In the function parameter, we pass the color value in the RGBA format – a set of four values, each in the range from 0 to 255. At the output, we get a two-byte RGB565 value in the range from 0 to 65536.
1 2 3 |
print(rgba_rgb565([188, 0, 0, 255])) # 47104 |
To save the whole image, each of its pixels needs to be processed through our function, resulting in an array of values in RGB565 format, which can already be saved to a file.