Python Forum
Sort Matrices by Mean Value Obtained (OpenCV, Python and Numpy)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort Matrices by Mean Value Obtained (OpenCV, Python and Numpy)
#1
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?
Reply
#2
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 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to sort a list without .sort() function letmecode 3 3,371 Dec-28-2020, 11:21 PM
Last Post: perfringo
  Editing images using python and opencv caaaameron_ 6 3,048 May-06-2020, 10:55 AM
Last Post: caaaameron_
  [split] Manual Sort without Sort function fulir16 2 3,118 Jun-02-2019, 06:13 AM
Last Post: perfringo
  Manual Sort without Sort function dtweaponx 26 48,616 Jun-01-2019, 06:02 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020