numpy - np.full 笔记

np.full是NumPy中用于创建填充指定值的数组的函数。以下是详细说明:

基本语法

numpy.full(shape, fill_value, dtype=None, order='C')

参数说明

  • shape: 数组的形状(元组或整数)
  • fill_value: 填充值
  • dtype: 数据类型(可选)
  • order: 内存布局,'C'或'F'(可选)

基本用法示例

1. 创建一维数组

import numpy as np

# 创建长度为5,填充值为7的数组
arr1 = np.full(5, 7)
print(arr1)  # [7 7 7 7 7]

# 指定数据类型
arr2 = np.full(5, 3.14, dtype=np.float32)
print(arr2)  # [3.14 3.14 3.14 3.14 3.14]

2. 创建二维数组

# 创建3x4的数组,填充值为10
arr2d = np.full((3, 4), 10)
print(arr2d)
# [[10 10 10 10]
#  [10 10 10 10]
#  [10 10 10 10]]

# 填充字符串
str_arr = np.full((2, 3), 'hello', dtype='

3. 创建三维数组

# 创建2x3x4的数组,填充值为255
arr3d = np.full((2, 3, 4), 255, dtype=np.uint8)
print(f"形状: {arr3d.shape}")
print(f"填充值: {arr3d[0, 0, 0]}")

在图像处理中的应用

1. 创建空白图像

import cv2
import numpy as np

# 创建纯黑图像
black_img = np.full((480, 640, 3), 0, dtype=np.uint8)

# 创建纯白图像
white_img = np.full((480, 640, 3), 255, dtype=np.uint8)

# 创建灰色图像
gray_img = np.full((480, 640, 3), 128, dtype=np.uint8)

# 创建特定颜色图像(蓝色)
blue_img = np.full((480, 640, 3), [255, 0, 0], dtype=np.uint8)  # BGR格式

# 显示图像
cv2.imshow('White Image', white_img)
cv2.imshow('Blue Image', blue_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
 
  

2. 创建Alpha通道

# 读取图像
img = cv2.imread('image.png')
h, w, c = img.shape

# 创建完全不透明的Alpha通道
alpha_channel = np.full((h, w, 1), 255, dtype=np.uint8)

# 添加Alpha通道
img_with_alpha = np.concatenate([img, alpha_channel], axis=2)
print(f"原图形状: {img.shape}")
print(f"添加Alpha后: {img_with_alpha.shape}")

# 创建半透明Alpha通道
semi_transparent = np.full((h, w, 1), 128, dtype=np.uint8)
img_semi = np.concatenate([img, semi_transparent], axis=2)
 
  

3. 创建掩码

# 创建全掩码(全部选中)
mask_all = np.full((480, 640), 255, dtype=np.uint8)

# 创建空掩码(全部不选中)
mask_none = np.full((480, 640), 0, dtype=np.uint8)

# 创建圆形掩码
mask_circle = np.full((480, 640), 0, dtype=np.uint8)
center = (320, 240)
radius = 100
cv2.circle(mask_circle, center, radius, 255, -1)

与其他NumPy函数的比较

1. np.zeros vs np.full

# 使用np.zeros
zeros_arr = np.zeros((3, 4))
print("np.zeros:")
print(zeros_arr)

# 使用np.full填充0
full_zeros = np.full((3, 4), 0)
print("np.full with 0:")
print(full_zeros)

# 结果相同,但np.full更灵活

2. np.ones vs np.full

# 使用np.ones
ones_arr = np.ones((3, 4))
print("np.ones:")
print(ones_arr)

# 使用np.full填充1
full_ones = np.full((3, 4), 1)
print("np.full with 1:")
print(full_ones)

你可能感兴趣的:(numpy,笔记,opencv)