我正在尝试遍历图像的像素,更具体地说是我通过ImageGrab模块获取的屏幕截图。这是我的代码:
from PIL import ImageGrab as ig
import numpy as np
from pynput.mouse import Controller
from pynput.keyboard import Key
from pynput import keyboard
mouse= Controller()
def onpress(key):
try:
pressed_key= key.char
except AttributeError:
pressed_key= str(key)[4:]
if pressed_key == 'esc':
print('Quitting process')
return False
elif pressed_key == 'space':
mousepos= mouse.position
pic= ig.grab()
arr= np.array(pic)
print(f'Pixel color at {mousepos}: RGB{arr[mousepos]}')
# here the error is raised
with keyboard.Listener(on_press= onpress) as listener:
listener.join()
我想在按下空格键时检查鼠标位置像素的RGB颜色。它适用于“最左上角”像素,下面是一些输出示例:
1) Pixel color at (150, 193): RGB[242 243 244]
2) Pixel color at (579, 302): RGB[0 0 0]
3) Pixel color at (887, 108): RGB[145 89 4]
但是当我在屏幕的右下角稍微移动鼠标(从中心到右下角一点点)时,会出现如下错误:
Traceback (most recent call last):
File "imagegrab.py", line 64, in <module>
listener.join()
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\_util\__init__.py", line 199, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\marca\Anaconda3\lib\site-packages\six.py", line 692, in reraise
raise value.with_traceback(tb)
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\_util\__init__.py", line 154, in inner
return f(self, *args, **kwargs)
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\keyboard\_win32.py", line 237, in _process
self.on_press(key)
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\_util\__init__.py", line 75, in inner
if f(*args) is False:
File "imagegrab.py", line 42, in onpress
print(f'{count}) Pixel color at {mousepos}: RGB{arr[mousepos]}')
IndexError: index 1152 is out of bounds for axis 0 with size 1080
如果使用加载图像,则不会出现此错误
pixels= pic.load()
print(f'{count}) Pixel color at {mousepos}: RGB{pixels[mousepos]}')
效果很好(这里我指的是屏幕的左上角和右下角):
1) Pixel color at (0, 0): RGB(56, 36, 12)
2) Pixel color at (1914, 1016): RGB(22, 15, 5)
我认为这与笔记本电脑的屏幕DPI有关,就像以前一样,我不得不像以前一样in this Github thread应用建议的this kind of screen-capture problem.
如您所见,错误(1152)中显示的数组索引溢出了高清屏幕的普通1920x1080分辨率。我不知道如何解决此问题,所以我希望我已经清楚了,有人可以帮助我。