I have a list of .jpg images and i am trying to extract the dominant color from google cloud vision API - https://cloud.google.com/vision/docs/drag-and-drop
The below piece of function sometimes extracts the correct RGB values but sometimes it extracts incorrect RGB values as well. What should i change in the below code so that it always picks the dominant color with highest RGB percentage. i.e the first RGB value from the left.
def dominat_color(image):
response = client.image_properties(image=image)
props = response.image_properties_annotation
max_frac=0.0
#print('Properties:', props.dominant_colors.colors[0].red,",",props.dominant_colors.colors[0].green,",",props.dominant_colors.colors[0].blue,",",dominant_colors.colors[0].pixel_fraction)
for color in props.dominant_colors.colors:
var1=float(color.pixel_fraction)*100
#var1=float(color.percent)
if (var1 > max_frac):
max_frac=var1
var2=int(color.color.red)
var3=int(color.color.green)
var4=int(color.color.blue)
#print("\nRGB: ", var2,",",var3,",",var4,",", (var1))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
return var2,var3,var4
creds = service_account.Credentials.from_service_account_file(r'xxxx.json') #credentials
client = vision.ImageAnnotatorClient(credentials=creds,)
Sample Output:
Image_name Red Green Blue
k1.jpg 240 125 16
The red,green and blue values should be the left most RGB values in gcp --> https://cloud.google.com/vision/docs/drag-and-drop under properties tab i am just trying to extract the first RGB values from the left.
For your requirement, you can use a list in python to store the values and find the dominant value from the left. You can check the below sample code which you can use for your use case.
Code :
def dominat_color(image):
from google.cloud import vision
import io
client = vision.ImageAnnotatorClient()
image_uri = image
image = vision.Image() # Py2+3 if hasattr(vision, 'Image') else vision.types.Image()
image.source.image_uri = image_uri
response = client.image_properties(image=image)
props = response.image_properties_annotation
#print('Properties:', props.dominant_colors.colors[0].red,",",props.dominant_colors.colors[0].green,",",props.dominant_colors.colors[0].blue,",",dominant_colors.colors[0].pixel_fraction)
max_frac=0.0
lst = []
for color in props.dominant_colors.colors:
var1=float(color.pixel_fraction)*100
if (var1 > max_frac):
max_frac = var1
var2=int(color.color.red)
lst.append(var2)
var3=int(color.color.green)
lst.append(var3)
var4=int(color.color.blue)
lst.append(var4)
rmax = max(lst)
index = lst.index(rmax)
print(lst[index],lst[index+1],lst[index+2])
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
dominat_color(image_path)
Output :