【OpenCV 例程300篇】07. 图像的创建(np.zeros)

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

【OpenCV 例程300篇】07. 图像的创建(np.zeros)

OpenCV 中图像对象的数据结构是 ndarray 多维数组,因此可以用 Numpy 创建多维数组来生成图像。特别对于空白、黑色、白色、随机等特殊图像,用 Numpy 创建图像非常方便。

Numpy 可以使用 np.zeros() 等方法创建指定大小、类型的图像对象,也可以使用 np.zeros_like() 等方法创建与已有图像大小、类型相同的新图像。

函数说明:

numpy.empty(shape[, dtype, order]) # 返回一个指定形状和类型的空数组
numpy.zeros(shape[, dtype, order]) # 返回一个指定形状和类型的全零数组
numpy.ones(shape[, dtype, order]) # 返回一个指定形状和类型的全一数组

numpy.empty_like(img) # 返回一个与图像 img 形状和类型相同的空数组
numpy.zeros_like(img) # 返回一个与图像 img 形状和类型相同的全零数组
numpy.ones_like(img) # 返回一个与图像 img 形状和类型相同的全一数组

参数说明:

  • shape:整型元组,定义返回多维数组的形状
  • dtype:数据类型,定义返回多维数组的类型,可选项
  • img:ndarray 多维数组,表示一个灰度或彩色图像

基本例程:


    height, width, channels = 400, 300, 3
    imgEmpty = np.empty((height, width, channels), np.uint8)
    imgBlack = np.zeros((height, width, channels), np.uint8)
    imgWhite = np.ones((height, width, channels), np.uint8) * 255

    img1 = cv2.imread("../images/imgLena.tif", flags=1)
    imgBlackLike = np.zeros_like(img1)
    imgWhiteLike = np.ones_like(img1) * 255

    import os
    randomByteArray = bytearray(os.urandom(height * width * channels))
    flatNumpyArray = np.array(randomByteArray)
    imgRGBRand = flatNumpyArray.reshape(height, width, channels)

    imgGrayWhite = np.ones((height, width), np.uint8) * 255
    imgGrayBlack = np.zeros((height, width), np.uint8)
    imgGrayEye = np.eye(width)
    randomByteArray = bytearray(os.urandom(height*width))
    flatNumpyArray = np.array(randomByteArray)
    imgGrayRand = flatNumpyArray.reshape(height, width)

    print("Shape of image: gray {}, RGB {}".format(imgGrayRand.shape, imgRGBRand.shape))
    cv2.imshow("DemoGray", imgGrayRand)
    cv2.imshow("DemoRGB", imgRGBRand)
    cv2.imshow("DemoBlack", imgBlack)
    key = cv2.waitKey(0)

本例程的运行结果如下:

【OpenCV 例程300篇】07. 图像的创建(np.zeros)

(本节完)

【第1章:图像的基本操作】
06. 像素的编辑(img.itemset)
07. 图像的创建(np.zeros)
08. 图像的复制(np.copy)
09. 图像的裁剪(cv2.selectROI)
10. 图像的拼接(np.hstack)

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

Original: https://blog.csdn.net/youcans/article/details/121174586
Author: YouCans
Title: 【OpenCV 例程300篇】07. 图像的创建(np.zeros)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/637947/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球