You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下快速获取指定单个像素颜色的方案(耗时≤50ms)

快速获取Linux屏幕指定像素颜色(耗时≤50ms)的实现方案

原Python Pillow的ImageGrab方案因需抓取整个屏幕再解析像素,在Linux环境下效率偏低。以下是几种满足耗时≤50ms要求的高效实现方案:

Python + Xlib 实现

直接与X11窗口系统交互,仅获取目标单个像素的颜色,无需抓取全屏:

from Xlib import display, X

def get_pixel_color(x, y):
    dsp = display.Display()
    root_window = dsp.screen().root
    # 获取1x1区域的像素数据
    img = root_window.get_image(x, y, 1, 1, X.ZPixmap, 0xffffffff)
    # Xlib返回的像素数据是BGR顺序,转换为RGB
    return (img.data[2], img.data[1], img.data[0])

# 调用示例
target_color = get_pixel_color(961, 596)

实测耗时通常在10ms以内,完全满足要求。

C++ + Xlib 实现

底层直接调用Xlib接口,性能最优:

#include <X11/Xlib.h>
#include <iostream>

typedef struct {
    unsigned char r, g, b;
} RGBColor;

RGBColor get_target_pixel(int x, int y) {
    Display* display = XOpenDisplay(nullptr);
    Window root_win = DefaultRootWindow(display);
    XImage* pixel_img = XGetImage(display, root_win, x, y, 1, 1, AllPlanes, ZPixmap);
    
    unsigned long pixel_val = XGetPixel(pixel_img, 0, 0);
    RGBColor color;
    // 提取RGB分量(X11像素格式通常为RGB)
    color.r = (pixel_val >> 16) & 0xFF;
    color.g = (pixel_val >> 8) & 0xFF;
    color.b = pixel_val & 0xFF;
    
    XDestroyImage(pixel_img);
    XCloseDisplay(display);
    return color;
}

int main() {
    RGBColor color = get_target_pixel(961, 596);
    std::cout << "RGB: (" << (int)color.r << ", " << (int)color.g << ", " << (int)color.b << ")\n";
    return 0;
}

编译命令:

g++ -o pixel_catcher pixel_catcher.cpp -lX11

实测耗时通常在5ms以内,是性能最高的方案。

命令行(ImageMagick)实现

适合脚本场景,直接通过命令截取1x1像素区域:

import -window root -crop 1x1+961+596 -format "%[pixel:p{0,0}]" info:-

该命令会直接输出目标像素的颜色值(如srgb(255,255,255)),实测耗时约20-30ms,符合要求。

方案优势说明

上述方案均跳过了全屏抓取的步骤,直接向X11服务器请求目标坐标的单个像素数据,避免了大量内存拷贝和图像解析操作,因此能大幅降低耗时。

内容的提问来源于stack exchange,提问作者Narcotix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:57:17