【OpenCV 例程300篇】05. 图像的属性(np.shape)

专栏地址:『youcans 的 OpenCV 例程 300 篇』


【OpenCV 例程300篇】05. 图像的属性(np.shape)


OpenCV 中图像对象的数据结构是 ndarray 多维数组,因此 ndarray 数组的属性和操作方法也都适用于 OpenCV 的图像对象。

在这里插入图片描述

  • img.ndim:查看图像的维数,彩色图像的维数为 3,灰度图像的维数为 2。
  • img.shape:查看图像的形状,即图像栅格的行数(高度)、列数(宽度)、通道数。
  • img.size:查看图像数组元素总数,灰度图像的数组元素总数为像素数量,彩色图像的数组元素总数为像素数量与通道数的乘积。

基本例程:

    # 1.11 图像数组的属性
    imgFile = "../images/imgLena.tif"  # 读取文件的路径
    img1 = cv2.imread(imgFile, flags=1)  # flags=1 读取彩色图像(BGR)
    img2 = cv2.imread(imgFile, flags=0)  # flags=0 读取为灰度图像
    # cv2.imshow("Demo1", img1)  # 在窗口显示图像
    # key = cv2.waitKey(0)  # 等待按键命令

    # 维数(ndim), 形状(shape), 元素总数(size), 元素类型(dtype)
    print("Ndim of img1(BGR): {}, img2(Gray): {}".format(img1.ndim, img2.ndim))  # number of rows, columns and channels
    print("Shape of img1(BGR): {}, img2(Gray): {}".format(img1.shape, img2.shape))  # number of rows, columns and channels
    print("Size of img1(BGR): {}, img2(Gray): {}".format(img1.size, img2.size))  # size = rows * columns * channels
    print("Dtype of img1(BGR): {}, img2(Gray): {}".format(img1.dtype, img2.dtype))  # uint8

本例程的运行结果如下:

Ndim of img1(BGR): 3, img2(Gray): 2
Shape of img1(BGR): (512, 512, 3), img2(Gray): (512, 512)
Size of img1(BGR): 786432, img2(Gray): 262144
Dtype of img1(BGR): uint8, img2(Gray): uint8

通过资源管理器查看彩色图像和灰度图像的属性如下图,彩色图像的位深度为 24,灰度图像的位深度为 8。

在这里插入图片描述


(本节完)


【第1章:图像的基本操作】
01. 图像的读取(cv2.imread)
02. 图像的保存(cv2.imwrite)
03. 图像的显示(cv2.imshow)
04. 用 matplotlib 显示图像(plt.imshow)
05. 图像的属性(np.shape)


版权声明:
youcans@xupt 原创作品,转载必须标注原文链接:(https://blog.csdn.net/youcans/article/details/125112487)
Copyright 2022 youcans, XUPT
Crated:2021-11-18

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

youcans_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值