0

I'm trying to write a program on linux that does something if the pixels in an area aren't all the same color, for example:

if color not "255, 255, 255":
    #do something

this is what i have for one pixel:

import time, pyautogui
time.clock()
image = pyautogui.screenshot()
color = image.getpixel((1006, 553))
print(time.clock())
print(color)

I know how to get the color of a pixel using .getpixel() but that only gets one pixel

Basically, how do i get the color of an area of pixels when i know all the pixels in that area are the same color.

Also, as quick as possible, like 0.5s or under.

Fízli
  • 1
  • 2
  • Consider using a ranged `for` loop to go over all pixels in the area - if one or more doesn't match the previous pixel, the check fails. – Nick Reed Oct 16 '19 at 19:00
  • @NickReed wouldn't that be really slow though? – Fízli Oct 16 '19 at 19:04
  • Depends how big your image is. 0.5 seconds is a LOT of time for a program - it should be enough for any image of realistic size. Are you *certain* the area is all the same pixel, though, or is that what your code is trying to determine? – Nick Reed Oct 16 '19 at 19:06
  • What libraries are you using? I'm sure there are many different ones who have a `.getpixel()` method. A runtime goal of 0.5s is meaningless if we don't know anything about your data! – AMC Oct 16 '19 at 19:06
  • @Fízli That would depend on the size of the area. – Carcigenicate Oct 16 '19 at 19:07
  • @Carcigenicate about 640x170 pixels – Fízli Oct 16 '19 at 19:15
  • @Fízli So like 100k pixels. On my phone, a comparable operation takes 0.0112 seconds to process the data (timed using `timeit`, `n=1000`) That doesn't include the time needed to get the data though since that's highly dependant. – Carcigenicate Oct 16 '19 at 19:20
  • @Carcigenicate Cool! I'll try the `for` loop then. – Fízli Oct 16 '19 at 19:22
  • Just use Numpy (`np.var`) to calculate the variance of any subimage. If it is zero, there is no variation in the colour. – Mark Setchell Oct 17 '19 at 18:59

1 Answers1

0

I keep recommending it, but the scikit-image library is pretty great, and they have some really solid documentation and examples. I would recommend a combo of that and using numpy arrays directly. It is just a lot faster when working directly with pixels. You will have to convert the PIL image to a numpy array...but this should work with that:

import pyautogui
import numpy as np

image = pyautogui.screenshot()
np_image = np.array(image)

You can slice the image:

red_slice = np_image[0:50, 0:50,0]
red_mask = red_slice == 200

This would give you the values for red in the upper right 50x50 pixel area. red_mask is an array of True/False values whether each red value in that area is equal to 200. This can be repeated for the other channels as you see fit.

Peter Boone
  • 1,193
  • 1
  • 12
  • 20