You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无需保存文件直接使用PIL ImageGrab获取的图像进行结构相似度计算?

问题描述

尝试用skimage包对比两张图像的结构相似度,发现仅当使用本地保存的图像时功能正常,直接使用PIL的ImageGrab创建的图像(内容完全一致)时无法运行。

代码示例:

def structural_sim(img1, img2):
    sim, diff = structural_similarity(img1, img2, full=True)
    return sim

# 无法运行
tempScreen = ImageGrab.grab(bbox=(985,193,1895,704))
sim = structural_sim(tempScreen, cv2.imread('08-55-48.PNG', 0))

# 可以运行
tempScreen = ImageGrab.grab(bbox=(985,193,1895,704))
tempScreen.save("temp.PNG")
sim = structural_sim(cv2.imread('temp.PNG', 0), cv2.imread('08-55-48.PNG', 0))

报错信息:

AttributeError: shape. Did you mean: 'save'?

解决方法

报错核心原因是ImageGrab.grab()返回的是PIL Image对象,而skimage的structural_similarity()要求输入为numpy数组格式的图像数据,同时要保证两张图像的灰度/通道格式匹配。

无需保存再读取的修改代码如下:

import numpy as np
from skimage.metrics import structural_similarity
import cv2
from PIL import ImageGrab

def structural_sim(img1, img2):
    sim, diff = structural_similarity(img1, img2, full=True)
    return sim

# 直接处理截图结果
tempScreen = ImageGrab.grab(bbox=(985,193,1895,704))
# 将PIL图像转为灰度模式后再转成numpy数组
temp_screen_gray = np.array(tempScreen.convert('L'))
# 读取本地灰度图(和截图格式对齐)
local_img_gray = cv2.imread('08-55-48.PNG', 0)

# 计算相似度
sim = structural_sim(temp_screen_gray, local_img_gray)
print(sim)

关键步骤说明:

  • tempScreen.convert('L'):把PIL彩色截图转为单通道灰度模式,和cv2.imread(...,0)的输出格式保持一致
  • np.array(...):将PIL Image对象转换为numpy数组,让skimage能识别图像的shape属性,满足函数输入要求

内容的提问来源于stack exchange,提问作者Ferdi_ the_best

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:36:32