How to find the average colour of an image in Python with OpenCV?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to find the average colour of an image in Python with OpenCV in Python. So Here I am Explain to you all the possible Methods here.

How to find the average colour of an image in Python with OpenCV?

1. How to find the average colour of an image in Python with OpenCV?

If you put the image into OpenCV's BGR format, you can run this code that puts each pixel into one of four classifications:

2. find the average colour of an image in Python with OpenCV

If you put the image into OpenCV's BGR format, you can run this code that puts each pixel into one of four classifications:

Method 1

I was able to get the average color by using the following:

import cv2
import numpy
avg_color_per_row = numpy.average(myimg, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
print(avg_color)

Result:

[ 197.53434769  217.88439451  209.63799938]

Method 2

If you put the image into OpenCV’s BGR format, you can run this code that puts each pixel into one of four classifications:

blue-green-red-gray

In the code that follows we process the image used by Tonechas,

PROGRAM

import cv2 as cv
import numpy as np

img  = cv.cvtColor(np.array(image), cv.COLOR_RGB2BGR)
rows, cols, _ = img.shape

color_B = 0
color_G = 0
color_R = 0
color_N = 0 # neutral/gray color

for i in range(rows):
for j in range(cols):
k = img[i,j]
if k > k and k > k:
color_B = color_B + 1
continue
if k > k and k > k:
color_G = color_G + 1
continue
if k > k and k > k:
color_R = color_R + 1
continue
color_N = color_N + 1

pix_total = rows * cols
print('Blue:', color_B/pix_total, 'Green:', color_G/pix_total, 'Red:',  color_R/pix_total, 'Gray:',  color_N/pix_total)

OUTPUT

Blue: 0.2978447577378059 Green: 0.21166979188369564 Red: 0.48950158575827024 Gray: 0.0009838646202282567

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.