np.full
是NumPy中用于创建填充指定值的数组的函数。以下是详细说明:
numpy.full(shape, fill_value, dtype=None, order='C')
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]
# 创建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='
# 创建2x3x4的数组,填充值为255
arr3d = np.full((2, 3, 4), 255, dtype=np.uint8)
print(f"形状: {arr3d.shape}")
print(f"填充值: {arr3d[0, 0, 0]}")
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()
# 读取图像
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)
# 创建全掩码(全部选中)
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)
# 使用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更灵活
# 使用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)