-2

I want to calculate the mean for each pixel value and how to show them separatly.for example: Mean 124.34(red),124.44(green),124.67(blue),123.56(gray) I try like this...

 import numpy as np
 import math 
 img = Image.open('cameraman.jpg')
 h,w=img.size 
 #print(h,w)
 arr = np.array(img)
 total = 0 
for i in range(arr.shape[0]):
      for j in range(arr.shape[1]):
            total+=arr[(i,j)]
  a=h*w
mean=(total)/a
print("Mean Value is: ",np.mean)
petezurich
  • 9,280
  • 9
  • 43
  • 57
  • Possible duplicate of [How to find the average colour of an image in Python with OpenCV?](https://stackoverflow.com/questions/43111029/how-to-find-the-average-colour-of-an-image-in-python-with-opencv) – Cris Luengo Dec 01 '18 at 20:12

1 Answers1

1

Shortest answer (by Ruan B. ):

import cv2
import numpy
myimg = cv2.imread('image.jpg')
avg_color_per_row = numpy.average(myimg, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
print(avg_color)

Result:

     Blue           Green          Red
[ 197.53434769  217.88439451  209.63799938]

More extended, similar to you own method: If you use opencv, accessing a pixel returns an array with the BGR colors.

import cv2
import numpy as np

img = cv2.imread('your_image.jpg')

totalBlue = 0
totalGreen = 0
totalRed = 0
totalPixels = 0

for line in img:
    for px in line:
        totalBlue += px[0]
        totalGreen += px[1]
        totalRed += px[2]
        totalPixels += 1

meanBlue = totalBlue/totalPixels
meanGreen = totalGreen/totalPixels
meanRed = totalRed/totalPixels

To get the gray average you can load you image as a black and white image using

img = cv2.imread('your_image.jpg', 0)
J.D.
  • 4,511
  • 2
  • 7
  • 20