2022年 11月 9日

Python实现计算图像RGB均值

要求

存在一个文件夹内有若干张图像,需要计算每张图片的RGB均值,并计算全部图像的RGB均值。

代码

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Nov 1 10:43:29 2018
  4. @author: Administrator
  5. """
  6. import os
  7. import cv2
  8. import numpy as np
  9. path = 'C:/Users/Administrator/Desktop/rgb'
  10. def compute(path):
  11. file_names = os.listdir(path)
  12. per_image_Rmean = []
  13. per_image_Gmean = []
  14. per_image_Bmean = []
  15. for file_name in file_names:
  16. img = cv2.imread(os.path.join(path, file_name), 1)
  17. per_image_Bmean.append(np.mean(img[:,:,0]))
  18. per_image_Gmean.append(np.mean(img[:,:,1]))
  19. per_image_Rmean.append(np.mean(img[:,:,2]))
  20. R_mean = np.mean(per_image_Rmean)
  21. G_mean = np.mean(per_image_Gmean)
  22. B_mean = np.mean(per_image_Bmean)
  23. return R_mean, G_mean, B_mean
  24. if __name__ == '__main__':
  25. R, G, B= compute(path)
  26. print(R, G ,B)