如何计算numpy数组中图像的平均颜色? [英] How to calculate mean color of image in numpy array?

查看:62
本文介绍了如何计算numpy数组中图像的平均颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RGB图像已转换为numpy数组.我正在尝试使用numpy或scipy函数计算图像的平均RGB值.

RGB值表示为0.0-1.0之间的浮点,其中1.0 = 255.

示例2x2像素image_array:

  [[[0.0,0.0,0.0],[0.0,0.0,0.0]],[[1.0,1.0,1.0],[1.0,1.0,1.0]]] 

我尝试过:

  import numpynumpy.mean(image_array,axis = 0)` 

但是输出:

  [[0.5 0.5 0.5][0.5 0.5 0.5]] 

我想要的只是单个RGB平均值:

  [0.5 0.5 0.5] 

解决方案

您仅沿一个轴取平均值,而您需要沿两个轴取平均值:图像的高度和宽度.

尝试一下:

 >>>image_arrayarray([[[0.,0.,0.],[0.,0.,0.]],[[1.,1.,1.],[1.,1.,1.]]])>>>np.mean(image_array,axis = {0,1))数组([0.5,0.5,0.5]) 

由于文档将告诉您,您可以为 axis 参数指定一个元组,并指定要获取均值的坐标轴.

I have an RGB image that has been converted to a numpy array. I'm trying to calculate the average RGB value of the image using numpy or scipy functions.

The RGB values are represented as a floating point from 0.0 - 1.0, where 1.0 = 255.

A sample 2x2 pixel image_array:

[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
 [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]

I have tried:

import numpy
numpy.mean(image_array, axis=0)`

But that outputs:

[[0.5  0.5  0.5]
 [0.5  0.5  0.5]]

What I want is just the single RGB average value:

[0.5  0.5  0.5]

解决方案

You're taking the mean along only one axis, whereas you need to take the mean along two axes: the height and the width of the image.

Try this:

>>> image_array    
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 1.,  1.,  1.],
        [ 1.,  1.,  1.]]])
>>> np.mean(image_array, axis=(0, 1))
array([ 0.5,  0.5,  0.5])

As the docs will tell you, you can specify a tuple for the axis parameter, specifying the axes over which you want the mean to be taken.

这篇关于如何计算numpy数组中图像的平均颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆