1

I would like to have a function that randomly permute the value of each pixel according to the dimensions of the channels in the image using PIL.

I tried some methods but I didn't get the right result or it's too slow.

EDIT

Example: For the pixel 1 suppose that the values are R: 42 G: 13 B:37, we apply the function and for this pixel the new values will be R: 13 G: 42 B:37 (for this pixel the permutation was 0,1,2 -> 1,0,2) For 2 it will be another random permutation for example 0,1,2 -> 2, 1, 0 etc ...

Example

Boring Guy
  • 83
  • 2
  • 5
  • *"randomly permute... according to dimensions of channels"*? What does that mean - do you have an example please? – Mark Setchell Mar 19 '20 at 16:08
  • @MarkSetchell For the pixel (0,0) suppose that the values are R: 42 G: 13 B:37, we apply the function and for this pixel the new values will be R: 13 G: 42 B:37 (for this pixel the permutation was 0,1,2 -> 1,0,2) For another pixel (0,1) it will be another random permutation for example 0,1,2 -> 2, 1, 0 etc .... Do you understand my question now? – Boring Guy Mar 19 '20 at 16:17
  • @Divakar has the solution here, you need to shuffle along axis=2... https://stackoverflow.com/a/55317373/2836621 – Mark Setchell Mar 19 '20 at 17:49
  • Sorry, if you didn't know you can convert your PIL Image to Numpy array like this `na = np.array(PILImage)` and use Divakar's technique then convert your Numpy array back to PIL Image with `PILImage = Image.fromarray(na)` – Mark Setchell Mar 19 '20 at 18:04
  • I'm intrigued as to the purpose of this? – Mark Setchell Mar 19 '20 at 18:06
  • We're going to try this as a data augmentation – Boring Guy Mar 19 '20 at 18:33
  • @MarkSetchell It's working. Thank you. – Boring Guy Mar 19 '20 at 18:47

1 Answers1

0

Little late but..

My first thought would be to do this in NumPy or another library

from itertools import permutations
import numpy as np
from PIL import Image
from random import randint

im = Image("./file")
permutations = list(permutations(range(3), 3))  # All possible permutations
rearranged = np.array(im)[..., list(permutations[randint(0, 5)])]
result = Image.fromarray(rearranged)

Something similar can be done without conversion to NumPy

from itertools import permutations
from PIL import Image
from random import randint

rgb_split = im.split()  # list corresponding to R, G, and B
permutations = list(permutations(range(3), 3))  # All possible permutations
selected = list(permutations[randint(0, 5)])
result = Image.merge("RGB", (rgb_split[selected[0]],
                         rgb_split[selected[1]],
                         rgb_split[selected[2]])
Roger
  • 46
  • 1
  • 3