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

如何使用Python OpenCV统一两张图片尺寸?解决resize参数错误

解决OpenCV resize报错:dsize参数格式错误

错误原因

你遇到的cv2.error核心问题是cv2.resize的dsize参数格式不匹配:

  • 图像的shape属性返回(高度, 宽度, 通道数)三维元组,但resize要求dsize是(宽度, 高度)的二维元组,传入first.shape会导致参数长度不符合要求。
  • 额外的np.asarray(second, dtype=int)完全多余,cv2.imread读取的图像本身就是uint8类型的numpy数组,强制转换为int可能破坏像素数据格式,引发后续异常。

修正后的完整代码

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

# 读取两张图片
first = cv2.imread('1.png')
second = cv2.imread('3.png')

# 将第二张图缩放至与第一张图相同尺寸
# dsize参数格式为(目标宽度, 目标高度),对应first.shape[1](宽)和first.shape[0](高)
second = cv2.resize(second, (first.shape[1], first.shape[0]))

# 转换为灰度图
first_gray = cv2.cvtColor(first, cv2.COLOR_BGR2GRAY)
second_gray = cv2.cvtColor(second, cv2.COLOR_BGR2GRAY)

# 计算两张图片的SSIM相似度
score, diff = structural_similarity(first_gray, second_gray, full=True)
print("Similarity Score: {:.3f}%".format(score * 100))

关键修正说明

  1. 移除多余的数组转换:直接删掉secondasnparray = np.asarray(second, dtype=int)这一行,保留cv2.imread返回的原始数组格式即可。
  2. 修正dsize参数:cv2.resize的尺寸参数必须遵循(宽度, 高度)的顺序,因此从first.shape中提取对应索引的值:
    • first.shape[0]:图像的高度
    • first.shape[1]:图像的宽度

内容的提问来源于stack exchange,提问作者Player 777

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:25:34