python自动计算图像数据集的RGB均值

时间:2022-08-25 21:34:57

本文实例为大家分享了python自动计算图像数据集的RGB均值,供大家参考,具体内容如下

图像数据集往往要进行去均值,以保证更快的收敛。

代码:

创建一个mean.py,写入如下代码。修改路径即可使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'''
qhy
2018.12.3
'''
import os
import numpy as np
import cv2
 
ims_path='C:/Users/my/Desktop/JPEGImages/'# 图像数据集的路径
ims_list=os.listdir(ims_path)
R_means=[]
G_means=[]
B_means=[]
for im_list in ims_list:
 im=cv2.imread(ims_path+im_list)
#extrect value of diffient channel
 im_R=im[:,:,0]
 im_G=im[:,:,1]
 im_B=im[:,:,2]
#count mean for every channel
 im_R_mean=np.mean(im_R)
 im_G_mean=np.mean(im_G)
 im_B_mean=np.mean(im_B)
#save single mean value to a set of means
 R_means.append(im_R_mean)
 G_means.append(im_G_mean)
 B_means.append(im_B_mean)
 print('图片:{} 的 RGB平均值为 \n[{},{},{}]'.format(im_list,im_R_mean,im_G_mean,im_B_mean) )
#three sets  into a large set
a=[R_means,G_means,B_means]
mean=[0,0,0]
#count the sum of different channel means
mean[0]=np.mean(a[0])
mean[1]=np.mean(a[1])
mean[2]=np.mean(a[2])
print('数据集的BGR平均值为\n[{},{},{}]'.format( mean[0],mean[1],mean[2]) )
#cv.imread()读取Img时候将rgb转换为了bgr,谢谢taylover-pei的修正。

终端运行: python mean.py

结果示例如下:

python自动计算图像数据集的RGB均值

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/gusui7202/article/details/84751598