首页 > 解决方案 > 使用 Python 在全屏游戏中获取像素颜色

问题描述

我是一名 Python 初学者,试图从全屏游戏中获取最主要的颜色(使用 ColorTheif 模块)并将 RGB 值输出到文本文件。这是我到目前为止所得到的:(不是我写的)

import pyscreenshot as ImageGrab
# Configs
# smaller screenshot region -> faster screenshot and faster dominant color determination
# coordinates of top left and bottom right of rectangle: (x1, y1, x2, y2)
SCREENSHOT_REGION = (940, 520, 980, 560)
# enabling USE_COLORTHIEF will provide better results but will run slightly slower
# if True, uses ColorThief to grab dominant color, otherwise just use top left pixel color
USE_COLORTHIEF = True


def get_color(region, colorthief=True):
    """ Screenshot a portion of the screen and return the rgb tuple of the most dominant color """
    im = ImageGrab.grab(bbox=SCREENSHOT_REGION,
                        backend='mss', childprocess=False)
    if colorthief:  # use ColorThief module to grab dominant color from screenshot region
        from colorthief import ColorThief
        im.save('screenshot.png')
        color_thief = ColorThief('screenshot.png')
        color = color_thief.get_color(quality=1)  # dominant color

    else:
        color = im.getpixel((0, 0))  # return color of top left pixel of region

    return color


def set_light_color(color):
    """ Set lifx light color to provided rgb tuple """
    if sum(color) <= 30:  # color is very dark, basically black
        # set color to blue since this is the closest to darkness
        color = (0, 0, 100)

    rgb = ','.join(map(str, color))  # convert (r, g, b) -> rgb:r,g,b

    text_file = open('color.txt', 'w')
    text_file.write(rgb)
    print(rgb)
    return text_file


if __name__ == '__main__':
    prev_color = (0, 0, 0)
    while True:
        try:
            color = get_color(SCREENSHOT_REGION)
            if color != prev_color:
                set_light_color(color)
                prev_color = color
        except KeyboardInterrupt:
            # reset light to max brightness after stopping program
            set_light_color((255, 255, 255))
            break

这在桌面和窗口应用程序(如谷歌浏览器)上运行良好,但不适用于全屏游戏。如何让它在全屏游戏中工作?谢谢。

标签: pythonscreenshotfullscreengetpixelcolor-thief

解决方案


推荐阅读