Python opencv计算批量图片的BGR各自的均值
#coding:utf-8 #第一种方式 很慢很慢 自己写的如何计算均值 ''' import cv2 import os def access_pixels(frame): print(frame.shape) #shape内包含三个元素:按顺序为高、宽、通道数 height = frame.shape[0] weight = frame.shape[1] channels = frame.shape[2] value_b = 0 value_g = 0 value_r = 0 print("weight : %s, height : %s, channel : %s" %(weight, height, channels)) for row in range(height): #遍历高 for col in range(weight): #遍历宽 value_b = value_b + frame[row, col, 0] value_g = value_g + frame[row, col, 1] value_r = value_r + frame[row, col, 2] singlePicValue_b = value_b / (height * weight) singlePicValue_g = value_g / (height * weight) singlePicValue_r = value_r / (height * weight) return singlePicValue_b,singlePicValue_g,singlePicValue_r def computeMeanValue(path): imgList1 = os.listdir(path) mean_b = 0 mean_g = 0 mean_r = 0 for i in range(len(imgList1)): srcframe = cv2.imread(os.path.join(path,imgList1[i])) singlePicValue_b,singlePicValue_g,singlePicValue_r = access_pixels(srcframe) mean_b = mean_b + singlePicValue_b mean_g = mean_g + singlePicValue_g mean_r = mean_r + singlePicValue_r all_mean_b = mean_b / len(imgList1) all_mean_g = mean_g / len(imgList1) all_mean_r = mean_r / len(imgList1) print (i) return all_mean_b,all_mean_g,all_mean_r all_mean_b,all_mean_g,all_mean_r = computeMeanValue('./spinningData/src') print (all_mean_b,all_mean_g,all_mean_r) ''' #第二种方式 借助numpy 很快 几秒 import os import cv2 import numpy as np path = './spinningData/src' def compute(path): file_names = os.listdir(path) per_image_Rmean = [] per_image_Gmean = [] per_image_Bmean = [] for file_name in file_names: img = cv2.imread(os.path.join(path, file_name), 1) per_image_Bmean.append(np.mean(img[:,:,0])) per_image_Gmean.append(np.mean(img[:,:,1])) per_image_Rmean.append(np.mean(img[:,:,2])) R_mean = np.mean(per_image_Rmean) G_mean = np.mean(per_image_Gmean) B_mean = np.mean(per_image_Bmean) return R_mean, G_mean, B_mean if __name__ == '__main__': R, G, B= compute(path) print(R, G ,B)