Numpy扩充矩阵维度(np.expand_dims, np.newaxis)和删除维度(np.squeeze)的方法

本文介绍了使用Numpy进行矩阵维度变更的方法,包括np.newaxis和np.expand_dims用于增加维度,np.squeeze用于删除维度大小为1的维度。通过实例展示了如何操作矩阵的维度。

在操作矩阵的时候,不同的接口对于矩阵的输入维度要求不同,输入可能为1-D,2-D,3-D等等。下面介绍一下使用Numpy进行矩阵维度变更的相关方法。主要包括以下几种:

1、np.newaxis扩充矩阵维度

2、np.expand_dims扩充矩阵维度

3、np.squeeze删除矩阵中维度大小为1的维度


np.newaxis,np.expand_dims扩充矩阵维度:

import numpy as np

x = np.arange(8).reshape(2, 4)
print(x.shape)

# 添加第0维,输出shape -> (1, 2, 4)
x1 = x[np.newaxis, :]
print(x1.shape)

# 添加第1维, 输出shape -> (2, 1, 4)
x2 = np.expand_dims(x, axis=1)
print(x2.shape)

输出结果:

(2, 4)
(1, 2, 4)
(2, 1, 4)

np.squeeze降低矩阵维度:

"""
    squeeze 函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉
    用法:numpy.squeeze(a,axis = None)
     1)a表示输入的数组;
     2)axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
     3)axis的取值可为None 或 int 或 tuple of ints, 可选。若axis为空,则删除所有单维度的条目;
     4)返回值:数组
     5) 不会修改原数组;
"""


import numpy as np

print("#" * 40, "原始数据", "#" * 40)
x = np.arange(10).reshape(1, 1, 10, 1)
print(x.shape)
print(x)

print("#" * 40, "去掉axis=0这个维度", "#" * 40)
x_squeeze_0 = np.squeeze(x, axis=0)
print(x_squeeze_0.shape, x_squeeze_0)

print("#" * 40, "去掉axis=3这个维度", "#" * 40)
x_squeeze_3 = np.squeeze(x, axis=3)
print(x_squeeze_3.shape, x_squeeze_3)

print("#" * 40, "去掉axis=0, axis=1这两个维度", "#" * 40)
x_squeeze_0_1 = np.squeeze(x, axis=(0, 1))
print(x_squeeze_0_1.shape, x_squeeze_0_1)

print("#" * 40, "去掉所有1维的维度", "#" * 40)
x_squeeze = np.squeeze(x)
print(x_squeeze.shape, x_squeeze)

print("#" * 40, "去掉不是1维的维度,抛异常", "#" * 40)
try:
    x_squeeze = np.squeeze(x, axis=2)
    print(x_squeeze.shape, x_squeeze)
except Exception as e:
    print(e)

输出结果:

######################################## 原始数据 ########################################
(1, 1, 10, 1)
[[[[0]
   [1]
   [2]
   [3]
   [4]
   [5]
   [6]
   [7]
   [8]
   [9]]]]
######################################## 去掉axis=0这个维度 ########################################
(1, 10, 1) [[[0]
  [1]
  [2]
  [3]
  [4]
  [5]
  [6]
  [7]
  [8]
  [9]]]
######################################## 去掉axis=3这个维度 ########################################
(1, 1, 10) [[[0 1 2 3 4 5 6 7 8 9]]]
######################################## 去掉axis=0, axis=1这两个维度 ########################################
(10, 1) [[0]
 [1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]
 [9]]
######################################## 去掉所有1维的维度 ########################################
(10,) [0 1 2 3 4 5 6 7 8 9]
######################################## 去掉不是1维的维度,抛异常 ########################################
cannot select an axis to squeeze out which has size not equal to one

参考链接

import cv2 import numpy as np from PIL import Image import onnxruntime as ort import time class RMBG2(): def __init__(self, model_ptah) -> None: self.sess_opts = ort.SessionOptions() self.sess_opts.log_severity_level = 3 provider = ["CPUExecutionProvider"] #provider = ["CUDAExecutionProvider","CPUExecutionProvider"] self.session = ort.InferenceSession(model_ptah, providers=provider,sess_options=self.sess_opts) self.input_name = self.session.get_inputs()[0].name self.input_shape = (1024,1024) # [1024, 1024] #print(f"模型输入:{self.input_shape}") #self.output_name = self.session.get_outputs()[0].name #print(f"模型输出:{self.output_name}") #self.output_shape = self.session.get_outputs()[0].shape #print(f"模型输出:{self.output_shape}") def preprocess(self, image: np.ndarray) -> np.ndarray: if len(image.shape) < 3: image = np.expand_dims(image, axis=2) image = cv2.resize( image, self.input_shape, interpolation=cv2.INTER_LINEAR ) image = image.astype(np.float32) / 255.0 image = (image - 0.5) / 1.0 image = np.transpose(image, (2, 0, 1)) return np.expand_dims(image, axis=0) def forward(self, blob): outs = self.session.run(None, {self.input_name: blob}) outs = outs[0].squeeze(axis=0) return outs @staticmethod def postprocess(result: np.ndarray, original_size: tuple) -> np.ndarray: result = cv2.resize( np.squeeze(result), original_size[::-1], interpolation=cv2.INTER_LINEAR, ) max_val, min_val = np.max(result), np.min(result) result = (result - min_val) / (max_val - min_val) return (result * 255).astype(np.uint8) def infer(self, image): blob = self.preprocess(image) output = self.forward(blob) result_mask = self.postprocess(output, image.shape[:2]) #print(result_mask.shape) #show_img(result_mask) pil_mask = Image.fromarray(result_mask) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) pil_image = Image.fromarray(image) pil_image = pil_image.convert("RGBA") pil_mask = pil_mask.convert("L") output_image = Image.new("RGBA", pil_image.size, (0, 0, 0, 0)) output_image.paste(pil_image, (0, 0), pil_mask) return output_image if __name__ == '__main__': # 模型下载 pip install modelscope # from modelscope import snapshot_download # model_dir = snapshot_download('AI-ModelScope/RMBG-2.0') # bria-rmbg-2.0.onnx (1.4模型)或 model_quantized.onnx (2.0模型) model_path = r"C:\Users\chaoguog\.cache\modelscope\hub\models\AI-ModelScope\RMBG-2___0\onnx\model_quantized.onnx" # 模型路径 tast = RMBG2(model_path ) img_path = r"66.png" img =cv2.imread(img_path) start = time.time() output_image = tast.infer(img) end = time.time() total = round((end - start), 2) print(f"耗时:{total} s") print("完成抠图") output_image.save('99_'+img_path) output_image.show()
最新发布
09-23
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值