【问题标题】:Wrong pixel color with Python?Python的像素颜色错误?
【发布时间】:2020-12-07 08:09:24
【问题描述】:

我试图从屏幕左上角的坐标 x = 386, y = 1131 处获取像素颜色。

当我跑步时

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)

在 python 中它给了我#2f3136 这绝对是错误的颜色。

应该是 #fb8908 就像 AppleScript 中的这个脚本给我的:

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

我还尝试在 Python 版本中反转 x 和 y,但它仍然给了我橙色以外的另一种颜色。 我做错了什么?

【问题讨论】:

  • 试试print('#%02x%02x%02x' % PIL.ImageGrab.grab((x,y,x+1,y+1)).getpixel((0,0)))x, y = 386, 1131
  • 我刚跑了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))) 但终端返回:TypeError: not all arguments converted during string formatting
  • 尝试在您的预期区域周围抓取 50-100 像素并将它们保存为文件,以查看您是否在正确的区域内查看。
  • 我该怎么做?
  • 我认为返回的图片是RGBA模式,所以使用print('#%02x%02x%02x' % ImageGrab.grab((x,y,x+1,y+1)).getpixel((0,0))[:3])

标签: python macos applescript


【解决方案1】:

经过一番尝试,我终于找到了解决方案。 我受到here 主题的启发,并搜索了一个解决方案以从屏幕上获取屏幕截图。 我不知道为什么 AppleScript 和 Python 给出不同的十六进制代码,但最重要的是 Python 返回橙色。

这里是代码

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

感谢 @MarkSetchell 和 @acw1668 帮助我。

【讨论】:

  • 为什么使用pix[1,1]而不使用pix[0,0]
  • 因为我不认为图像有一个以 [0,0] 为坐标的像素。
  • 它们是索引。 Python 索引从零开始。我想知道pix[0,0] 给出的结果与ImageGrab.grab() 相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多