我想计算每个像素值的平均值以及如何分别显示它们,例如: 平均值124.34(红色),124.44(绿色),124.67(蓝色),123.56(灰色) 我这样尝试...
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)
答案 0 :(得分:1)
最短的答案(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)
结果:
Blue Green Red
[ 197.53434769 217.88439451 209.63799938]
更多扩展,类似于您自己的方法: 如果您使用opencv,则访问像素将返回具有BGR颜色的数组。
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
要获得灰度平均值,您可以使用
将图像加载为黑白图像img = cv2.imread('your_image.jpg', 0)