Home > database >  How to find the closest pixel points indexes of one RGB list from another RGB list?
How to find the closest pixel points indexes of one RGB list from another RGB list?

Time:01-06

I have been working for some Image Processing Task. I have provided all details what I want to do below.

What I intend to do:

I have two lists

colorlist = around 500 rgb values (From picture 1 which I already have)

color = around 1200 or more RGB values (From picture 2 which I have also)

Note: Above lists can vary their size like colorlist can be sometimes bigger than color

Now I want to find all the elements of color to get its closest pixel values in colorlist then return the closest pixel values in a form of list [suppose list_1] and finally return the indexes of that list [list_1] from Picture 2 whole Image RGB List.

For Example:

picture2 = 
[[ 59 218 186]
 [161 144 250]
 [133 165 249]
 [135 125 125]
 ...
 [59  58 145]
 [153  144 155]
 [ 61 225  87]
 [153 149  63]]

colorlist = 

[[ 59 218 186]
 [161 144 250]
 [133 165 249]
 ...
 [155  58 184]
 [ 61 225  87]
 [153 149  63]]

color = 

[[201 224 194]
 [121  93 158]
 [ 99 143 153]
 ...
 [193  67 171]
 [ 80  49  94]
 [125 121 219]]


#Suppose these two values are closest found  in color array from colorlist
list1 = [(161, 144, 250), (133, 165, 249) ] 



index = [2 , 3] #Found from picture2 whole image array

###the index here is assumed for demonstration it can be larger or different from colorlist





What I tried:

Method 1: Using numpy linalg norm

def closest_points(color,colorlist):
  for x in range (0, len(color):
    dist = np.linalg.norm(colorlist - color[x], axis=1)
    tmp = colorlist[np.argmin(dist)]
    list1.append(tmp)
  return list1

ERROR THROWS: Same as Method 2 (Dimension Error)

Method 2: Using Scipy KDTree

def closest_points(color,colorlist):
  for x in range (0, len(color):
    tree = sp.KDTree(colorlist)
    tmp = colorlist[tree.query(color[x])[1]]
    list1.append(tmp)
  return list1

ERROR THROWS:

super().__init__(data, leafsize, compact_nodes, copy_data,
File "_ckdtree.pyx", line 560, in scipy.spatial._ckdtree.cKDTree.__init__
ValueError: data must be 2 dimensions


Method 3:

def closest_points(rgb,newlist):
    r, g, b = rgb
    color_diffs = []
    for x in newlist:
        cr, cg, cb = x
        color_diff = math.sqrt((r - cr)**2   (g - cg)**2   (b - cb)**2)
        color_diffs.append((color_diff, x))
    return min(color_diffs)[1]

for x in range (0, len(color)):
    
    tmp = closest_color(color[x],colorlist)
    list1.append(tmp)

ERROR THROWS:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Hope my question is clear. Thanks for the help !

CodePudding user response:

I found the solution of it by myself. In method 2 there is no need to iterate.

def closest_points(color,colorlist): 
  tree = sp.KDTree(colorlist)
  tmp = colorlist[tree.query(color)[1]]
return tmp

  • Related