mcphervi
mcphervi

Reputation: 9

Trying to take a screenshot, convert to grayscale, then get the average pixel value

I apologize but I'm completely new to python.. I'm trying to take a screenshot of the main monitor, then convert to grayscale, then find the average of the grayscale pixel values - I will want this to loop with a defined sleep period as well between loops. I've been trying to read a number of articles with example code for various components of this, and have the following - however I am not seeing an average pixel value printed by pycharm when I use the run command..

One possibility I tried:

import numpy as np
from PIL import ImageGrab
import cv2

def process_img(image):
    original_image = image
    # convert to gray
    processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    return processed_img


def screen_record():
    while True:
        printscreen_pil =  ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None)
        image = np.array(printscreen_pil.getdata(),dtype='uint8')\
        .reshape((printscreen_pil.size[1],printscreen_pil.size[0],3))
        new_screen = process_img(screen)
        mean = (np.mean(new_screen))
        print (mean)
        sleep(30)

I also found an article which directly imports the screenshot as a numpy array which would produce the following:

import numpy as np
from PIL import ImageGrab
import cv2


def process_img(image):
    original_image = image
    # convert to gray
    processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    return processed_img

def main():
    while True:
        screen = np.array(ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None))
        new_screen = process_img(screen)
        print(np.mean(new_screen))
        sleep(30)
        

However, neither code seems to produce an actual output in pycharm as far as I can tell.

Upvotes: 0

Views: 293

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

You only define functions in your program, but never actually call them.

Add a new, unindented line at the bottom of your second program to actually call main() like this:

def main():
    while True:
        ...
        ... your code
        ...

main()

Upvotes: 1

Related Questions