Python Forum
Sort Matrices by Mean Value Obtained (OpenCV, Python and Numpy) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Sort Matrices by Mean Value Obtained (OpenCV, Python and Numpy) (/thread-17961.html)



Sort Matrices by Mean Value Obtained (OpenCV, Python and Numpy) - danny_paez - May-01-2019

Hi, I need help.

I'm working with OpenCV and Python.

I separated the green, red and blue components of an RGB image with OpenCV and Python. Then subdivide each of these matrices into 8x8 submatrices in order to work with them. So far, this is already done.

For each of the 8x8 submatrices that it generates, I need to obtain the mean of each one, and order the matrices in descending order according to the mean obtained. I'm stuck in this. I need help.

The code that I have so far is the following

import cv2
import numpy as np 

img = cv2.imread("6.jpg")
b,g,r = cv2.split(img)


def sub_matrices(color_channel):
    matrices = []

    for i in range(int(color_channel.shape[0]/8)):
        for j in range(int(color_channel.shape[1]/8)):
            matrices.append(color_channel[i*8:i*8 + 8, j*8:j*8+8])
    return matrices

#returns list of sub matrices
r_submatrices = sub_matrices(r)
g_submatrices = sub_matrices(g)
b_submatrices = sub_matrices(b)

print (r_submatrices)
print (g_submatrices)
print (b_submatrices)

for i in r_submatrices:

	x = np.array(i)
	
	print('mean: ',np.mean(x))
I am using numpy to get the mean, but then I do not understand very well how I can order these matrices, depending on the value I get in the mean?


RE: Sort Matrices by Mean Value Obtained (OpenCV, Python and Numpy) - scidam - May-03-2019

You can use numpy.argsort to sort by mean values,
look at the following example (for red channel):

r_inds = np.argsort(np.array(r_submatrices).reshape(-1, len(r_submatrices)).mean(axis=0))[::-1]
np.array(r_submatrices)[r_inds]  # sorted array