Issue
I have fond online a function to extract and display the dominant colors of an image. To save time, I want to iterate only on the non-zeros pixels instead of the whole image. However the way I changed the function raises an error :
if row != [0,0,0]:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Here is the modified code :
def dominantColor(image) :
from matplotlib.pyplot import imshow, show
from scipy.cluster.vq import whiten
from scipy.cluster.vq import kmeans
import pandas as pd
r = []
g = []
b = []
for row in image :
if row != [0,0,0]: #the part I added to the original code
print(row)
for temp_r, temp_g, temp_b in row:
r.append(temp_r)
g.append(temp_g)
b.append(temp_b)
image_df = pd.DataFrame({'red': r, 'green': g, 'blue': b})
image_df['scaled_color_red'] = whiten(image_df['red'])
image_df['scaled_color_blue'] = whiten(image_df['blue'])
image_df['scaled_color_green'] = whiten(image_df['green'])
cluster_centers, _ = kmeans(image_df[['scaled_color_red','scaled_color_blue','scaled_color_green']], 3)
dominant_colors = []
red_std, green_std, blue_std = image_df[['red','green','blue']].std()
for cluster_center in cluster_centers:
red_scaled, green_scaled, blue_scaled = cluster_center
dominant_colors.append((
red_scaled * red_std / 255,
green_scaled * green_std / 255,
blue_scaled * blue_std / 255
))
imshow([dominant_colors])
show()
return dominant_colors
How should I correct my iteration loop to remove the error and have only the non-zeros values of my image ? (NB : the image is actually mask * original_image
)
Solution
You need to add .all()
method after that comparison if you want co compare arrays element wise. So if (row == [0,0,0]).all()
.
import numpy as np
image = np.array([
[0, 0, 0],
[1, 0, 0],
[0, 0, 1],
])
for row in image:
if not (row == [0, 0, 0]).all():
print(row)
Result:
[1 0 0]
[0 0 1]
Answered By - Piotr Grzybowski Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.