在 Windows 7 上使用 Python 快速获取屏幕上某些像素的颜色

2022-01-18 00:00:00 python colors pixel windows-7 screen

问题描述

我需要获取屏幕上或活动窗口中某些像素的颜色,我需要这样做快速.我试过使用 win32gui 和 ctypes/windll,但它们太慢了.这些程序中的每一个都获得 100 像素的颜色:

I need to get the color of some pixels on the screen or from the active window, and I need to do so quickly. I've tried using win32gui and ctypes/windll, but they're much too slow. Each of these programs gets the color of 100 pixels:

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 秒.是什么让它这么慢?

Each of these takes about 1.75 seconds. I need a program like this to take less than 0.1 seconds. What's making it so slow?

我正在使用 Python 3.x 和 Windows 7.如果您的解决方案需要我使用 Python 2.x,请将我链接到显示如何同时安装 Python 3.x 和 2.x 的文章.我看了看,但不知道该怎么做.

I'm working with Python 3.x and Windows 7. If your solution requires I use Python 2.x, please link me to an article showing how to have Python 3.x and 2.x both installed. I looked, but couldn't figure out how to do this.


解决方案

我遇到了同样的问题,并解决了它(在 Java 中,在 C# 中).解决方案背后的主要思想是 GetPixel from screen 很慢,你无法解决这个问题.但由于您需要一些像素,您可以一次获得一堆.

I had this same exact problem, and solved it (in Java, in C#). The main idea behind the solution is GetPixel from screen is slow, and you can't fix that. But as you need some pixels, you can get a bunch of them all at once.

获得 64 像素所需的时间快了 98 倍.

The time that it took to get 64 pixels was 98 times faster.

相关文章