I'm trying to write a program to take a screenshot of my game and detect the rgb values of the pixel in the middle, in a loop.
This was my initial code:
import pyautogui
def get_middle_pixel_color():
screen_width, screen_height = pyautogui.size()
middle_x = screen_width // 2
middle_y = screen_height // 2
pixel_func = pyautogui.pixel # Assign the pixel function to a local variable
while True:
pixel_color = pixel_func(middle_x, middle_y) # Use the local variable for pixel function
print(f"Pixel color: {pixel_color}")
if __name__ == '__main__':
get_middle_pixel_color()
While this worked when focused on the desktop or some other programs, as soon as I focus on the game, values turned to (0, 0, 0).
First thing I tried was to set the game to windowed mode, that didn't help.
Then I found these answers on stackoverflow:
The second answer has a working code snippet written in c++ so I tried converting that to python using chatgpt. This was the result:
import ctypes
def get_middle_pixel_color():
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)
middle_x = screen_width // 2
middle_y = screen_height // 2
# Get the device context for the entire screen
screen_dc = user32.GetDC(None)
# Create a compatible device context
mem_dc = gdi32.CreateCompatibleDC(screen_dc)
# Create a bitmap compatible with the screen device context
bmp = gdi32.CreateCompatibleBitmap(screen_dc, 1, 1)
# Select the bitmap object into the compatible device context
gdi32.SelectObject(mem_dc, bmp)
# Define the value of SRCCOPY manually
SRCCOPY = 0xCC0020
while True:
# Copy the pixel color from the screen to the bitmap
gdi32.BitBlt(mem_dc, 0, 0, 1, 1, screen_dc, middle_x, middle_y, SRCCOPY)
# Retrieve the color value of the pixel
pixel_color = gdi32.GetPixel(mem_dc, 0, 0)
# Extract the individual color components (red, green, blue)
red = pixel_color & 0xFF
green = (pixel_color >> 8) & 0xFF
blue = (pixel_color >> 16) & 0xFF
print(f"Pixel color (R, G, B): ({red}, {green}, {blue})")
if __name__ == '__main__':
get_middle_pixel_color()
This version worked well when focusing on both the desktop and the game, tough it only worked when the game was on the main menu and settings part.
The game I'm trying this on is valorant, the color becomes black when I start a match.