1

I am working on a program that takes a screenshot and saves the pixels in a Numpy Array with 3 axis (X, Y, and the RGB value itself) and cannot properly sum the last axis.

I have searched up information on this topic, and although I have tried several things such as "Axis=2" I have made no progress. I would like to stay away from for loops. Because although they work I feel as though that defeats the purpose of sum in the first place.

#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)

I am hoping to get the result that the variables red green and blue show their respective value of the sum of all of the pixels on the screen, however I am currently getting "1468800" for all of them. Any help is appreciated, Thanks.

kmario23
  • 57,311
  • 13
  • 161
  • 150
Grimm_boss
  • 15
  • 4

1 Answers1

0

If I understand the problem correctly, simply setting axis=2 should work. Here is a working example:

# 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)

P.S. Since I'm on *nix, I cannot check the working of PIL.ImageGrab because that works only on MacOS and Windows.

kmario23
  • 57,311
  • 13
  • 161
  • 150
  • I tried this out and am unsure as to what problem I'm facing, as it seems that it should work. this is the new code ``` while(True): #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, axis=2) green = np.sum(screen[[1][0]]) blue = np.sum(screen[[2][0]]) ``` and im getting this error " File "ValueError: setting an array element with a sequence." – Grimm_boss Apr 16 '19 at 00:30
  • @Grimm_boss so the problem is that you should not assign to any of `red`, `green`, or `blue`. see this thread for more info: [valueerror-setting-an-array-element-with-a-sequence](https://stackoverflow.com/a/47482672) – kmario23 Apr 16 '19 at 00:45