首页 > 解决方案 > 在 Numpy 中沿第三轴求和时遇到问题

问题描述

我正在开发一个程序,该程序截取屏幕截图并将像素保存在具有 3 轴(X、Y 和 RGB 值本身)的 Numpy 数组中,并且无法正确总结最后一个轴。

我已经搜索了有关此主题的信息,尽管我尝试了几种方法,例如“Axis=2”,但我没有取得任何进展。我想远离 for 循环。因为虽然它们有效,但我觉得这首先违背了 sum 的目的。

#Imports
import numpy as np
from PIL import ImageGrab

#Define Hight and Width of screen
height = 1080
width = 1920


#Capture screen with by taking individual RGB values in an array
screen = np.array(ImageGrab.grab(bbox=(0,0,width,height)))

red = np.sum(screen[[0][0]])
green = np.sum(screen[[1][0]])
blue = np.sum(screen[[2][0]])

print(red,blue,green)

我希望得到的结果是变量红色绿色和蓝色显示它们各自的值是屏幕上所有像素的总和,但是我目前得到的结果都是“1468800”。任何帮助表示赞赏,谢谢。

标签: pythonnumpypython-imaging-libraryrgbnumpy-ndarray

解决方案


如果我正确理解了这个问题,简单的设置就axis=2可以了。这是一个工作示例:

# sample RGB image to work with
In [24]: from skimage import data
In [25]: astronaut = data.astronaut()
In [26]: astronaut.shape
Out[26]: (512, 512, 3)

# sum the RGB values (R+G+B)
In [30]: astronaut_summed = np.sum(astronaut, axis=2)
In [31]: astronaut_summed.shape
Out[31]: (512, 512)

PS 由于我在 *nix 上,我无法检查它的工作,PIL.ImageGrab因为它仅适用于 MacOS 和 Windows。


推荐阅读