playwright+python UI自动化测试中实现图片颜色和像素对比

python 复制代码
def compare_image(expect_path, actual_path, output_path, color_diff_threshold=10.0,max_diff_pixels=100):
    # 读取图片
    img1 = cv2.imread(expect_path)
    img2 = cv2.imread(actual_path)
    if img1.shape != img2.shape:
        img2 = cv2.resize(img2, (img1.shape[1], img1.shape))

    # ---------------------- 颜色差异对比(LAB空间) ----------------------
    # 转换为LAB颜色空间(更贴近人类视觉)
    img1_lab = cv2.cvtColor(img1, cv2.COLOR_BGR2LAB)
    img2_lab = cv2.cvtColor(img2, cv2.COLOR_BGR2LAB)

    # 计算色差(欧氏距离)
    color_diff = np.sqrt(np.sum((img1_lab - img2_lab) ** 2, axis=2))
    mean_color_diff = np.mean(color_diff)

    if mean_color_diff > color_diff_threshold:
        # 增强色差可视化(将差异值映射到0-255)
        color_diff_vis = (color_diff * 255 / np.max(color_diff)).astype(np.uint8)
        cv2.imwrite(output_path, color_diff_vis)
        raise ValueError(f"颜色差异过大:{mean_color_diff:.2f} > {color_diff_threshold}")

    # ---------------------- 像素差异对比(灰度空间) ----------------------
    # 灰度化 + 模糊处理
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    blur1 = cv2.GaussianBlur(gray1, (5, 5), 0)
    blur2 = cv2.GaussianBlur(gray2, (5, 5), 0)

    # 计算像素差异
    diff = cv2.absdiff(blur1, blur2)
    _, thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)

    # 统计显著差异像素数
    diff_pixels = np.sum(thresh == 255)
    if diff_pixels > max_diff_pixels:
        # 标记差异区域(红框)
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        result = img2.copy()
        for cnt in contours:
            # if cv2.contourArea(cnt) > min_contour_area:
            x, y, w, h = cv2.boundingRect(cnt)
            cv2.rectangle(result, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv2.imwrite(output_path, result)
        raise ValueError(f"差异像素数超过阈值:{diff_pixels} > {max_diff_pixels}")

1、准备好基线图(expect_path)

2、playwright打开页面,截取元素图片(actual_path)

3、直接将基线图和实际元素图片传入对比方法对比,当差异超过预期,则会在实际元素图片上红框标记出差异部分保存到output_path

需要注意的是:

如果是表单截图,则需要等待所有的字段都加载完

如果是图片预览截图,则需要等待图片彻底打开到最大

相关推荐
花酒锄作田10 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪14 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽14 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战14 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋20 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama