Home > Software engineering >  Reorder/reshape NP array as image
Reorder/reshape NP array as image

Time:01-23

I can grab the colours of an image with

import re
from PIL import Image
import numpy as np

docName = "pal.png"
img = Image.open(docName).convert("RGB")

# Make into Numpy array
npArr = np.array(img)

# Arrange all pixels into a tall column of 3 RGB values and find unique rows (colours)
colours, counts = np.unique(npArr.reshape(-1,3), axis=0, return_counts=1)

# Change to string
npStr = np.array2string(colours, separator = ", ")
pal = re.sub(r"\s?\[|\]\,|]]", "", npStr)
print(pal)


Using a small 4 colour sample image

4 colour image We have four colours:

51, 51, 51 179, 198, 15 255, 204, 0 255, 255, 255

Trouble is NP re-orders them in order of brightness. I want to preserve the order as reading it from top left to bottom right.

I need them in this order:

 51,  51,  51 # near black
255, 255, 255 # white
255, 204,   0 # yellow
179, 198,  15 # green

Can that be easily done with NumPy?

CodePudding user response:

I don't know exactly what the image is, but you could use the return_index=True parameter in np.unique. This way you get the indices of the first occurrences for corresponding colours in colours. If you then sort these indices, you can index colours from your image to get the unique colours while preserving the order.

colours, idx, counts = np.unique(
    npArr.reshape(-1,3), axis=0, return_index=True, return_counts=True
)

print(npArr.reshape(-1,3)[np.sort(idx)])
  • Related