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

如何使用OpenCV获取图片列表中的最大宽度?

获取图片的最大宽度

你可以通过以下步骤实现需求:

  1. OpenCV读取的图像以numpy数组形式存储,其shape属性返回(高度, 宽度, 通道数),因此取索引1即可获取图片宽度。
  2. 遍历读取到的图像,收集所有宽度值后用max()函数取最大值;也可以在遍历过程中实时更新最大宽度。

方案一:保留图像同时获取最大宽度

import cv2

image_names = ["POPI_133.png", "POPI_134.png", "POPI_135.png", "POPI_135.png"]
images = []
widths = []

for name in image_names:
    img = cv2.imread(name)
    # 增加读取校验,避免因图片不存在/损坏导致报错
    if img is not None:
        images.append(img)
        # 提取宽度(shape[1]对应宽度)
        widths.append(img.shape[1])

# 计算最大宽度,处理空列表情况(所有图片读取失败)
max_width = max(widths) if widths else 0
print(f"最大宽度:{max_width}")

方案二:仅获取最大宽度(不保留图像,节省内存)

import cv2

image_names = ["POPI_133.png", "POPI_134.png", "POPI_135.png", "POPI_135.png"]
max_width = 0

for name in image_names:
    img = cv2.imread(name)
    if img is not None:
        current_width = img.shape[1]
        # 实时更新最大宽度
        if current_width > max_width:
            max_width = current_width

print(f"最大宽度:{max_width}")

内容的提问来源于stack exchange,提问作者Issac Boera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:30:44