Effective way to change pixel intensity value (pixel-shuffling)?

Hi,
I want to change pixel value in random way! (pixel-shuffling)

For example,
if I use CIFAR10 data,
then I could get [3,32,32] pixel tensors, and each pixel can get integer value between [0~255]
What I want to do is
I want to make new mapping! for 256 values. This can be named pixel-shuffling.
for example, [0,1,2,255] → randint(255) => [244,3,0,255]

I want to ask you if there is better way to do pixel-shuffling.
I only can think for-loop to change each pixel value like below…

(X is given input [batch_size, 3,32,32])
(key is mapping dictionary {0:244, 1:3, , previous_value: result_value,}

    result_X  = X
    for batch_i in range(X.shape[0]):
        for channel_j in range(X.shape[1]):
            for row_k in range(X.shape[2]):
                for col_l in range(X.shape[3]):
                    previous = X[batch_i][channel_j][row_k][col_l]
                    previous = previous.item()
                    result_X[batch_i][channel_j][row_k][col_l] = key[previous]

is there effective ways to do pixel-shuffling ?

You could probably directly index the mapping as seen here:

# create input
x = torch.arange(2*3*32*32).to(torch.uint8)
x = x.view(2, 3, 32, 32)
print(x)

# create mapping by shifting it by 1
mapping = torch.arange(0, 256, dtype=torch.uint8) + 1
# mapping[index] would contain the new value

# index into mapping directly and assign to the result tensor
result = mapping[x.view(-1).long()]
# reshape back
result = result.view(2, 3, 32, 32)
print(result)

# your approach
X = x.clone()
result_X  = X
key = mapping
for batch_i in range(X.shape[0]):
    for channel_j in range(X.shape[1]):
        for row_k in range(X.shape[2]):
            for col_l in range(X.shape[3]):
                previous = X[batch_i][channel_j][row_k][col_l]
                previous = previous.item()
                result_X[batch_i][channel_j][row_k][col_l] = key[previous]

# compare
print((result == result_X).all())
> tensor(True)
1 Like

Thank you so much for sharing your answer!!
your way is way more effective!