Last Updated: February 25, 2016
·
223
· tiger-222

Efficient swaping with slices and bytearray

Imagine you have an array with BGR values. You want to swap B and R to have RGB values (example taken from the Python MSS module).

pixels_len = len(pixels)
pixels = bytearray(pixels)
pixels[2:pixels_len:3], pixels[0:pixels_len:3] = \
    pixels[0:pixels_len:3], pixels[2:pixels_len:3]
pixels = bytes(pixels)

This code is the most efficient I found for that purpose. And it is insanely fast ...

If you want to try your solution with real data, check this challenge.

Source: blog.jmsinfo.co