当前位置: 首页 > news >正文

检测图片指定多个位子像素坐标与目标比较。外部图像识别。如红色,黄色,绿色。。。

上图先~


 

import pygame
import cv2
import tkinter as tk
from tkinter import filedialog# 初始化 Pygame
pygame.init()# 屏幕尺寸
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Design By Tim")# 加载支持中文的字体文件(请确保路径正确)
font_path = r"C:\Windows\Fonts\simhei.ttf"
font_size = 25
font = pygame.font.Font(font_path, font_size)
fontOKNG = pygame.font.Font(font_path, 200)# 全局变量
image_path = None
background_image = None
resized_cv_image = None  # 存储缩放后的OpenCV图像
image_rect = None        # 存储图片在窗口中的位置和尺寸 (left, top, width, height)
pixel_positions = []     # 存储输入的像素信息 (x, y, target_color)
input_active = False     # 当前是否处于输入状态
input_type = None        # 当前输入类型 ('x', 'y', 'color')
current_input = ""       # 当前输入内容
temp_x = None            # 临时存储x坐标
temp_y = None            # 临时存储y坐标def load_image(path):"""加载图片"""try:image = cv2.imread(path)if image is None:raise FileNotFoundErrorreturn imageexcept Exception:return Nonedef resize_image_to_fit(image):"""将图片缩放以完全填充窗口,保持宽高比,返回缩放后的图片和位置信息"""img_height, img_width = image.shape[:2]screen_ratio = SCREEN_WIDTH / SCREEN_HEIGHTimg_ratio = img_width / img_heightif img_ratio > screen_ratio:new_width = SCREEN_WIDTHnew_height = int(new_width / img_ratio)else:new_height = SCREEN_HEIGHTnew_width = int(new_height * img_ratio)resized_image = cv2.resize(image, (new_width, new_height))left = (SCREEN_WIDTH - new_width) // 2top = (SCREEN_HEIGHT - new_height) // 2return resized_image, (left, top, new_width, new_height)def get_pixel_color(win_x, win_y):"""获取窗口坐标(win_x, win_y)处的颜色"""global resized_cv_image, image_rectif resized_cv_image is None or image_rect is None:return Noneleft, top, width, height = image_rect# 转换为图片内部坐标img_x = win_x - leftimg_y = win_y - topif 0 <= img_x < width and 0 <= img_y < height:try:bgr_color = resized_cv_image[img_y, img_x]rgb_color = (bgr_color[2], bgr_color[1], bgr_color[0])  # 转换为RGBreturn "#{:02x}{:02x}{:02x}".format(*rgb_color)except IndexError:return Nonereturn Nonedef draw_ui():"""绘制 UI 界面"""global input_active, input_type, current_inputscreen.fill((0, 0, 0))  # 黑色背景# 绘制背景图片if background_image is not None:screen.blit(background_image, (0, 0))# 显示输入状态if input_active:input_box_y = SCREEN_HEIGHT - 60pygame.draw.rect(screen, (200, 200, 200), (50, input_box_y, 600, 40))input_text = font.render(f"{input_type.upper()}: {current_input}", True, (0, 0, 0))screen.blit(input_text, (60, input_box_y + 5))# 绘制已添加的检测点for idx, (x, y, color) in enumerate(pixel_positions):# 绘制坐标点pygame.draw.circle(screen, (255, 0, 0), (x, y), 5)# 显示序号label = font.render(str(idx+1), True, (0, 255, 0))screen.blit(label, (x + 10, y - 10))# 显示匹配结果if pixel_positions:all_matched, mismatches = check_pixel_colors()status_text = "OK" if all_matched else "NG"status_color = (0, 255, 0) if all_matched else (255, 0, 0)status_surface = fontOKNG.render(status_text, True, status_color)screen.blit(status_surface, (SCREEN_WIDTH-200, 10))# 显示不匹配信息if mismatches:y_offset = 150for idx, target, detected in mismatches:info = f"位置{idx}: 目标={target} 实际={detected}"text = font.render(info, True, (255, 0, 0))screen.blit(text, (10, SCREEN_HEIGHT - y_offset))y_offset += 40pygame.display.flip()def check_pixel_colors():"""检查所有像素位置的颜色是否匹配"""mismatches = []all_matched = Truefor idx, (x, y, target_color) in enumerate(pixel_positions):detected_color = get_pixel_color(x, y)if not detected_color:all_matched = Falsemismatches.append((idx+1, target_color, "无效坐标"))elif detected_color.lower() != target_color.lower():all_matched = Falsemismatches.append((idx+1, target_color, detected_color))return all_matched, mismatches# 按钮样式
button_width = 150
button_height = 50
button_margin = 20
button_color = (100, 100, 100)  # 灰色背景
button_text_color = (255, 255, 255)  # 白色文字# 按钮位置
load_button_rect = pygame.Rect(button_margin, button_margin, button_width, button_height)
detect_button_rect = pygame.Rect(button_margin, button_margin * 2 + button_height, button_width, button_height)
start_button_rect = pygame.Rect(button_margin, button_margin * 3 + button_height * 2, button_width, button_height)def draw_buttons():"""绘制按钮"""pygame.draw.rect(screen, button_color, load_button_rect)pygame.draw.rect(screen, button_color, detect_button_rect)pygame.draw.rect(screen, button_color, start_button_rect)load_text = font.render("加载图片", True, button_text_color)detect_text = font.render("目标输入", True, button_text_color)start_text = font.render("开始检测", True, button_text_color)screen.blit(load_text, (load_button_rect.x + (load_button_rect.width - load_text.get_width()) // 2, load_button_rect.y + (load_button_rect.height - load_text.get_height()) // 2))screen.blit(detect_text, (detect_button_rect.x + (detect_button_rect.width - detect_text.get_width()) // 2, detect_button_rect.y + (detect_button_rect.height - detect_text.get_height()) // 2))screen.blit(start_text, (start_button_rect.x + (start_button_rect.width - start_text.get_width()) // 2, start_button_rect.y + (start_button_rect.height - start_text.get_height()) // 2))import timehover_start_time = None
hover_position = Nonedef check_mouse_hover():global hover_start_time, hover_positionmouse_x, mouse_y = pygame.mouse.get_pos()if hover_position == (mouse_x, mouse_y):if hover_start_time is None:hover_start_time = time.time()elif time.time() - hover_start_time >= 3:show_coordinates(mouse_x, mouse_y)else:hover_start_time = Nonehover_position = (mouse_x, mouse_y)def show_coordinates(x, y):color = get_pixel_color(x, y)if color:text = font.render(f"X: {x}, Y: {y}, Color: {color}", True, (106, 90, 205))screen.blit(text, (x + 10, y - 30))pygame.display.update()time.sleep(3)  # 显示3秒def main():global image_path, background_image, resized_cv_image, image_rectglobal pixel_positions, input_active, input_type, current_input, temp_x, temp_yrunning = Trueclock = pygame.time.Clock()while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.MOUSEBUTTONDOWN:mouse_x, mouse_y = pygame.mouse.get_pos()if load_button_rect.collidepoint(mouse_x, mouse_y):# 加载图片逻辑root = tk.Tk()root.withdraw()image_path = filedialog.askopenfilename()if image_path:global background_image, resized_cv_image, image_rectcv_image = load_image(image_path)if cv_image is not None:resized_cv_image, image_rect = resize_image_to_fit(cv_image)background_image = pygame.image.frombuffer(resized_cv_image.tobytes(), resized_cv_image.shape[1::-1], "BGR")elif detect_button_rect.collidepoint(mouse_x, mouse_y):# 检测坐标输入逻辑input_active = Trueinput_type = 'x'current_input = ""temp_x = Nonetemp_y = Noneelif start_button_rect.collidepoint(mouse_x, mouse_y):# 开始逻辑all_matched, mismatches = check_pixel_colors()print("检测结果:", "通过" if all_matched else "失败")if mismatches:print("不匹配的点:")for idx, target, detected in mismatches:print(f"位置{idx}: 目标={target} 实际={detected}")elif event.type == pygame.KEYDOWN and input_active:if event.key == pygame.K_RETURN:if input_type == 'x':try:temp_x = int(current_input)input_type = 'y'current_input = ""except ValueError:input_active = Falseelif input_type == 'y':try:temp_y = int(current_input)input_type = 'color'current_input = ""except ValueError:input_active = Falseelif input_type == 'color':color = current_inputif temp_x is not None and temp_y is not None and color:pixel_positions.append((temp_x, temp_y, color))input_active = Falseelif event.key == pygame.K_BACKSPACE:current_input = current_input[:-1]else:current_input += event.unicodecheck_mouse_hover()draw_ui()draw_buttons()pygame.display.flip()clock.tick(18)  # 提高帧率到60FPSpygame.quit()if __name__ == "__main__":main()

相关文章:

  • HTML 从标签到动态效果的基础
  • [计算机科学#4]:二进制如何塑造数字世界(0和1的力量)
  • JAVA:线程池
  • H3C华三:单臂路由配置
  • 用Postman验证IAM Token的实际操作
  • 2025年五一数学建模竞赛AI辅助全网专业性第一
  • 网络安全入门综述
  • 乐理学习笔记(一)---节拍与音符
  • Python依据卫星TLE轨道根数,计算可见时间窗口
  • CMake:设置编译C++的版本
  • 卧式五轴加工中心市场报告:智能制造浪潮下的机遇与挑战
  • 国内外都有哪些医药医学方面的指南检索数据库?
  • 基于强化学习的用于非刚性图像配准的引导式超声采集|文献速递-深度学习医疗AI最新文献
  • 前端性能优化(实践篇)
  • 简单了解跨域问题
  • JAVA中Spring全局异常处理@ControllerAdvice解析
  • 说一下react更新的流程
  • TCP/IP模型(互联网协议模型)
  • 大模型相关问题解答
  • 系统优化双引擎:正负反馈如何驱动系统进化?
  • 财政部农业农村司司长吴奇修接受纪律审查和监察调查
  • 深圳一季度GDP为8950.49亿元,同比增长5.2%
  • A股三大股指收跌:地产股领跌,银行股再度走强
  • 伊朗港口爆炸已致40人死亡
  • 今年3月全国查处违反中央八项规定精神问题16994起
  • 加拿大警方:已确认有9人在温哥华驾车撞人事件中遇难