在Windows 7上Python快速获取屏幕某些像素的颜色
我需要快速获取屏幕上或活动窗口中一些像素的颜色。我尝试过使用win32gui和ctypes/windll,但速度太慢了。这些程序每次获取100个像素的颜色:
import win32gui
import time
time.clock()
for y in range(0, 100, 10):
for x in range(0, 100, 10):
color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x , y)
print(time.clock())
还有
from ctypes import windll
import time
time.clock()
hdc = windll.user32.GetDC(0)
for y in range(0, 100, 10):
for x in range(0, 100, 10):
color = windll.gdi32.GetPixel(hdc, x, y)
print(time.clock())
每个程序大约需要1.75秒。我希望这样的程序能在0.1秒内完成。是什么让它们这么慢呢?
我正在使用Python 3.x和Windows 7。如果你的解决方案需要我使用Python 2.x,请给我一个链接,告诉我如何同时安装Python 3.x和2.x。我查过,但没弄明白怎么做。
5 个回答
12
感谢Margus的指引,我专注于在提取像素信息之前先获取图像。这里有一个可行的解决方案,使用的是Python图像库(PIL),这个库需要Python 2.x版本。
import ImageGrab
import time
time.clock()
image = ImageGrab.grab()
for y in range(0, 100, 10):
for x in range(0, 100, 10):
color = image.getpixel((x, y))
print(time.clock())
我觉得这已经够简单了。这个过程平均需要0.1秒,虽然比我希望的稍慢,但速度还是可以接受的。
关于同时安装Python 3.x和2.x的事情,我把这个问题单独分开了,详细内容可以查看这个新问题。我在这方面还有些麻烦,但总体上是能正常工作的。
16
这样做比一直使用 getpixel
要好,而且速度更快。
import ImageGrab
px = ImageGrab.grab().load()
for y in range(0, 100, 10):
for x in range(0, 100, 10):
color = px[x, y]
参考资料:Image.load