使用Python实现获取屏幕像素颜色值

2025-06-08 15:50

本文主要是介绍使用Python实现获取屏幕像素颜色值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用Python实现获取屏幕像素颜色值》这篇文章主要为大家详细介绍了如何使用Python实现获取屏幕像素颜色值,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...

一、一个小工具,按住F10键,颜色值会跟着显示。

完整代码

import tkinter as tk
import pyautogui
import keyboard
 
class ColorViewer:
    def __init__(self):
        self.root = tk.Tk()
        self.root.overrideredirect(True)  # 无边框
        self.root.wm_attributes("-topmost", 1)  # 最前
        self.root.configure(bg="black")
        self.root.geometry("140x60")
 
        self.color_frame = tk.Frame(self.root, width=24, height=48, bg="white")
        self.color_frame.place(x=5, y=5)
 
        self.hex_label = tk.Label(self.root, text="#-----www.chinasem.cn-", font=("Consolas", 13), bg="black", fg="white")
        self.hex_label.place(x=35, y=5)
 
        self.coord_label = tk.Label(self.root, text="(0000,0000)", font=("Consolas", 11), bg="black", fg="white")
        self.coord_label.place(x=35, y=30)
 
        self.update_loop()
 
        self.root.withdraw()  # 初始隐藏
        self.root.mainloop()
 
    def update_loop(self):
        if keyboard.is_pressed("F10"):
            x, y = pyautogui.position()
            r, g, b = pyautogui.screenshot(region=(x, y, 1, 1)).getpixel((0, 0))
            hex_color = "#{:02x}{:02x}{:02x}".format(r, g, b)
 
            self.color_frame.configure(bg=hex_color)
            self.hex_label.configure(text=hex_color)
            self.coord_label.configure(text=f"({x},{y})")
 
            # 自动移动窗口,避免遮挡鼠标
            screen_w = self.root.winfo_screenwidth()
            screen_h = self.root.winfo_screenheight()
            win_w, win_h = 140, 60
            offset = 20
 
            pos_x = x + offset
            pos_y = y + offset
            if pos_x + win_w > screen_w:
                pos_x http://www.chinasem.cn= x - win_w - offset
            if pos_y + win_h > screen_h:
                pos_y = y - win_h - offset
 
            self.root.geometry(f"{win_w}x{win_h}+{pos_x}+{pos_y}")
            self.root.deiconify()
   http://www.chinasem.cn     else:
            self.root.withdraw()
 
        self.root.after(30, self.update_loop)  # 循环检查
 
if __name__ == "__main__":
    ColorViewer()

二、样式示例

使用Python实现获取屏幕像素颜色值

三、方法补充

python获取像素颜色

使用image模块中的getpixel函数获得像素值。

GetPixel函数检索指定坐标点的China编程像素的RGB颜色值。

函数原型:COLORREF GetPixel(HDC hdc, int nXPos, int nYPos)

参数:

hdc:设备环境句柄。

nXPos:指定要检查的像素点的逻辑X轴坐标。

nYPos:指定要检查的像素点的逻辑Y轴坐标。

示例:

import Image
import sys
im = Image.open(sys.argv[1])
width = im.size[0]
height = im.size[1]
print "/* width:%d */"%(width)
print "/* height:%d */"%(height)
count = 0
for h in range(0, height):
for w in range(0, width):
pixel = im.getpixel((w, h))
for i in range(0,3):
count = (count+1)%16
if (count == 0):
print "0x%02x,/n"%(pixel[i]),
else:
print "0x%02x,"%(pixel[i]),

Python获取屏幕指定坐标处像素颜色

import ctypes
from ctypes import wintypes
from typing import Sequence, Generator
 
 
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32
 
# 定义类型
HWND = wihttp://www.chinasem.cnntypes.HWND
HDC = wintypes.HDC
HBITMAP = wintypes.HBITMAP
 
 
class BITMAPINFOHEADER(ctypes.Structure):
    _fields_ = [
        ("biSize", wintypes.dwORD),
        ("biWidth", wintypes.LONG),
        ("biHeight", wintypes.LONG),
        ("biPlanes", wintypes.WORD),
        ("biBitCount", wintypes.WORD),
        ("biCompression", wintypes.DWORD),
        ("biSizeImage", wintypes.DWORD),
        ("biXPelsPerMeter", wintypes.LONG),
        ("biYPelsPerMeter", wintypes.LONG),
        ("biClrUsed", wintypes.DWORD),
        ("biClrImportant", wintypes.DWORD)
    ]
 
class BITMAPINFO(ctypes.Structure):
    _fields_ = [
        ("bmiHeader", BITMAPINFOHEADER),
        ("bmiColors", wintypes.DWORD * 3)
    ]
 
 
def get_pixel_color(coords: Sequence[tuple[int, int]], hwnd: HWND) -> Generator[tuple[int, int, int], None, None]:
    rect = wintypes.RECT()
    user32.GetClientRect(hwnd, ctypes.byref(rect))
    width = rect.right - rect.left
    height = rect.bottom - rect.top
 
    # 创建内存设备上下文
    hdc_src = user32.GetDC(hwnd)
    hdc_dst = gdi32.CreateCompatibleDC(hdc_src)
    bmp = gdi32.CreateCompatibleBitmap(hdc_src, width, height)
    gdi32.SelectObject(hdc_dst, bmp)
 
    # 使用 BitBlt 复制窗口内容到内存设备上下文
    gdi32.BitBlt(hdc_dst, 0, 0, width, height, hdc_src, 0, 0, 0x00CC0020)  # SRCCOPY
 
    # 获取位图信息
    bmi = BITMAPINFO()
    bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
    bmi.bmiHeader.biWidth = width
    bmi.bmiHeader.biHeight = -height  # 负值表示自底向上
    bmi.bmiHeader.biPlanes = 1
    bmi.bmiHeader.biBitCount = 32
    bmi.bmiHeader.biCompression = 0
 
    # 创建缓冲区并获取位图数据
    buffer = ctypes.create_string_buffer(width * height * 4)
    gdi32.GetDIBits(hdc_dst, bmp, 0, height, buffer, ctypes.byref(bmi), 0)
 
    # 释放资源
    gdi32.DeleteObject(bmp)
    gdi32.DeleteDC(hdc_dst)
    user32.ReleaseDC(hwnd, hdc_src)
 
    # 遍历指定坐标并返回像素颜色
    for x, y in coords:
        if 0 <= x < width and 0 <= y < height:
            offset = (y * width + x) * 4
            color = buffer[offset:offset + 4]
            yield color[2], color[1], color[0]  # BGR -> RGB
        else:
            yield (0, 0, 0)

到此这篇关于使用Python实现获取屏幕像素颜色值的文章就介绍到这了,更多相关Python获取屏幕像素颜色值内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于使用Python实现获取屏幕像素颜色值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154958

相关文章

C#监听txt文档获取新数据方式

《C#监听txt文档获取新数据方式》文章介绍通过监听txt文件获取最新数据,并实现开机自启动、禁用窗口关闭按钮、阻止Ctrl+C中断及防止程序退出等功能,代码整合于主函数中,供参考学习... 目录前言一、监听txt文档增加数据二、其他功能1. 设置开机自启动2. 禁止控制台窗口关闭按钮3. 阻止Ctrl +

java如何实现高并发场景下三级缓存的数据一致性

《java如何实现高并发场景下三级缓存的数据一致性》这篇文章主要为大家详细介绍了java如何实现高并发场景下三级缓存的数据一致性,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 下面代码是一个使用Java和Redisson实现的三级缓存服务,主要功能包括:1.缓存结构:本地缓存:使

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么

mybatis中resultMap的association及collectio的使用详解

《mybatis中resultMap的association及collectio的使用详解》MyBatis的resultMap定义数据库结果到Java对象的映射规则,包含id、type等属性,子元素需... 目录1.reusltmap的说明2.association的使用3.collection的使用4.总

如何在Java Spring实现异步执行(详细篇)

《如何在JavaSpring实现异步执行(详细篇)》Spring框架通过@Async、Executor等实现异步执行,提升系统性能与响应速度,支持自定义线程池管理并发,本文给大家介绍如何在Sprin... 目录前言1. 使用 @Async 实现异步执行1.1 启用异步执行支持1.2 创建异步方法1.3 调用

Spring Boot配置和使用两个数据源的实现步骤

《SpringBoot配置和使用两个数据源的实现步骤》本文详解SpringBoot配置双数据源方法,包含配置文件设置、Bean创建、事务管理器配置及@Qualifier注解使用,强调主数据源标记、代... 目录Spring Boot配置和使用两个数据源技术背景实现步骤1. 配置数据源信息2. 创建数据源Be

Java中使用 @Builder 注解的简单示例

《Java中使用@Builder注解的简单示例》@Builder简化构建但存在复杂性,需配合其他注解,导致可变性、抽象类型处理难题,链式编程非最佳实践,适合长期对象,避免与@Data混用,改用@G... 目录一、案例二、不足之处大多数同学使用 @Builder 无非就是为了链式编程,然而 @Builder

在MySQL中实现冷热数据分离的方法及使用场景底层原理解析

《在MySQL中实现冷热数据分离的方法及使用场景底层原理解析》MySQL冷热数据分离通过分表/分区策略、数据归档和索引优化,将频繁访问的热数据与冷数据分开存储,提升查询效率并降低存储成本,适用于高并发... 目录实现冷热数据分离1. 分表策略2. 使用分区表3. 数据归档与迁移在mysql中实现冷热数据分

mybatis-plus QueryWrapper中or,and的使用及说明

《mybatis-plusQueryWrapper中or,and的使用及说明》使用MyBatisPlusQueryWrapper时,因同时添加角色权限固定条件和多字段模糊查询导致数据异常展示,排查发... 目录QueryWrapper中or,and使用列表中还要同时模糊查询多个字段经过排查这就导致只要whe

linux批量替换文件内容的实现方式

《linux批量替换文件内容的实现方式》本文总结了Linux中批量替换文件内容的几种方法,包括使用sed替换文件夹内所有文件、单个文件内容及逐行字符串,强调使用反引号和绝对路径,并分享个人经验供参考... 目录一、linux批量替换文件内容 二、替换文件内所有匹配的字符串 三、替换每一行中全部str1为st