0

I translated a grayscale picture into a matrix that contains the intensity values of each pixel as integers. Now I'm looking for a way to sort the matrix by its pixel intensity values. Take the following matrix for example:

enter image description here

The output should be:

enter image description here

I couldn't get the desired result using numpy.sort, does anyone have an idea how to do this?

EDIT: Here's the code:

import numpy as np
import matplotlib.pyplot as plt

# Pillow library, to manipulate images
from PIL import Image

# reading image with PIL module
original = Image.open('original_reduced.png')

# converting it to a numpy array. numpy arrays are easier to manipulate 
im_original = np.array(original)

#plt.imshow(im_original, cmap='gray', vmin=0, vmax=255)

# size of full image
im_original.shape

## size and cropping coordinates
s = 170
x, y = 85, 85

# crops image of his face
im = im_original[y:y+s, x:x+s]


## im_b should be "im" sorted
im_b = ???

#print(im)
#print(im_b)

plt.imshow(im_b, cmap='gray', vmin=0, vmax=255)

plt.show() 
3
  • Please share some example code of what you tried, including some sample data (could be in the code), so people can see what you're actually working on. (the reason to ask is that writing a trivial example using your images of data actually simply works with numpy.sort - so it's impossible to say why it doesn't for you, without seeing how you tried coding it) Commented Nov 3, 2021 at 23:35
  • 1
    Also see meta.stackoverflow.com/questions/285551/… Commented Nov 3, 2021 at 23:37
  • Need to convert it back to an image using PIL Image.fromarray(sorted_image) Commented Nov 3, 2021 at 23:45

1 Answer 1

3

You can sort the flattened array and reshape to original shape in Fortran-like order:

np.sort(a.ravel()).reshape(a.shape, order='F')

input:

a = np.array([[4,2,1,3],
              [6,5,7,8],
              [11,10,9,12]
             ])

output:

array([[ 1,  4,  7, 10],
       [ 2,  5,  8, 11],
       [ 3,  6,  9, 12]])
Sign up to request clarification or add additional context in comments.

1 Comment

I'd use ravel() instead of flatten() since a copy is not really needed at that point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.