Python实现计算图像RGB均值方式
更新时间:2020年06月04日 09:45:58 作者:蹦跶的小羊羔
这篇文章主要介绍了Python实现计算图像RGB均值方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
要求
存在一个文件夹内有若干张图像,需要计算每张图片的RGB均值,并计算全部图像的RGB均值。
代码
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 1 10:43:29 2018
@author: Administrator
"""
import os
import cv2
import numpy as np
path = 'C:/Users/Administrator/Desktop/rgb'
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)
这里需要注意cv2.imread()读取顺序为BGR问题。
注意
路径不能出现中文,不然容易出错。
错误如下:
TypeError: 'NoneType' object is not subscriptable
结果

补充知识:Image得到图片像素的RGB
我就废话不多说了,大家还是直接看代码吧!
from PIL import Image
image = Image.open('./3.png')
print(image)#查看mode是否等于RGB,
image_rgb = image.convert("RGB")
image_rgb.getcolors()
打印结果
<PIL.PngImagePlugin.PngImageFile image mode=P size=500x332 at 0x7F53383FADA0> [(10990, (192, 0, 128)),#10990表示像素总数,(192, 0, 128)表示RGB值 (7589, (224, 224, 192)), (5706, (192, 128, 128)), (3913, (0, 64, 0)), (137802, (0, 0, 0))]
以上这篇Python实现计算图像RGB均值方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
详解python中[-1]、[:-1]、[::-1]、[n::-1]使用方法
这篇文章主要介绍了详解python中[-1]、[:-1]、[::-1]、[n::-1]使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-04-04
关于tf.matmul() 和tf.multiply() 的区别说明
这篇文章主要介绍了关于tf.matmul() 和tf.multiply() 的区别说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-06-06
使用wxPython和pandas模块生成Excel文件的代码实现
在Python编程中,有时我们需要根据特定的数据生成Excel文件,本文将介绍如何使用wxPython和pandas模块来实现这个目标,文中通过代码示例给大家讲解的非常详细,具有一定的参考价值,需要的朋友可以参考下2024-05-05


最新评论