1

I'm trying to get the pixel color from the screen at the coordinates x = 386, y = 1131 from the top left hand corner of the screen.

When I run

import PIL.ImageGrab
from time import sleep
sleep(2)
rgb2 = PIL.ImageGrab.grab().load()[386,1131]
couleur = list(rgb2)
del couleur[3]
couleur = '#%02x%02x%02x' % tuple(couleur)
print(couleur)

in python it gives me #2f3136 which is definitely a wrong color.

It should be #fb8908 like this script in AppleScript gives me :

delay 2
set colour to ""
set colour to do shell script "screencapture -R386,1131,1,1 -t bmp $TMPDIR/test.bmp && 
              xxd -p -l 3 -s 54 $TMPDIR/test.bmp | 
                   sed 's/\\(..\\)\\(..\\)\\(..\\)/\\3\\2\\1/'"
display dialog colour

I also tried to invert the x and y in the Python version but it still gives me another color than orange. What am I doing wrong ?

RobC
  • 22,977
  • 20
  • 73
  • 80
Larwive
  • 87
  • 2
  • 9
  • Try `print('#%02x%02x%02x' % PIL.ImageGrab.grab((x,y,x+1,y+1)).getpixel((0,0)))` where `x, y = 386, 1131`. – acw1668 Aug 18 '20 at 07:27
  • I just ran `import PIL.ImageGrab from time import sleep sleep(2) x = 386 y = 1131 print('#%02x%02x%02x' % PIL.ImageGrab.grab((x,y,x+1,y+1)).getpixel((0,0)))` But the terminal returned : `TypeError: not all arguments converted during string formatting` – Larwive Aug 18 '20 at 07:33
  • Try grabbing 50-100 pixels around your expected area and saving them as a file to see if you are looking in the correct area. – Mark Setchell Aug 18 '20 at 07:35
  • How do I do that ? – Larwive Aug 18 '20 at 07:35
  • I think the returned image is in `RGBA` mode, so use `print('#%02x%02x%02x' % ImageGrab.grab((x,y,x+1,y+1)).getpixel((0,0))[:3])`. – acw1668 Aug 18 '20 at 07:35
  • There is no error while running but it still gives #2f3136. – Larwive Aug 18 '20 at 07:37
  • You better take a screen shot of the whole screen and inspect the pixel color using image editor program. – acw1668 Aug 18 '20 at 07:57
  • Instead of the full screen, I tried `from subprocess import call from time import sleep sleep(2) call(["screencapture", "-R386,1131,1,1", "screenshot.jpg"])` and it gets the right pixel to extract the color from. Now I just need to get its color. – Larwive Aug 18 '20 at 08:03

1 Answers1

0

After some tries, I finally got a solution. I got inspired with the topic here and searched a solution to get a screenshot from the screen. I don't know why AppleScript and Python give different hex code but the most important thing is that Python returns an orange color.

Here is the code

from PIL import Image
from time import sleep
from subprocess import call
sleep(2)
call(["screencapture", "-R386,1131,1,1", "screenshot.jpg"])
im = Image.open('/Users/kevinshao/screenshot.jpg')
pix = im.load()
print('#%02x%02x%02x' % pix[1,1][:3])

Thanks @MarkSetchell and @acw1668 for helping me.

Larwive
  • 87
  • 2
  • 9