数组、张量相关

1 数组

1.1 生成随机数组,并得到多维数组的最大值和最小值。

import numpy as np

x = np.arange(0, 9).reshape(3, 3)
max = np.min(x)
min = np.max(x)

print('type(x): ', type(x))
print('x.shape: ', x.shape)
print('max: %d , min: %d' % (max, min))

# type(x):  <class 'numpy.ndarray'>
# x.shape:  (3, 3)
# max: 0 , min: 8

1.2 数组的维度

在这里插入图片描述

代码如下:

X = np.array([[[1, 2, 3],[4, 5, 6],[7, 8, 9]],[[11, 12, 13],[14, 15, 16],[17, 18, 19]],[[21, 22, 23],[24, 25, 26],[27, 28, 29]]])
print(X.shape)
print(X)
'''
(3, 3, 3)
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[11 12 13]
  [14 15 16]
  [17 18 19]]

 [[21 22 23]
  [24 25 26]
  [27 28 29]]]
'''

Y1 = X[::2, :, :]
print(Y1.shape)
print(Y1)
'''
(2, 3, 3)
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[21 22 23]
  [24 25 26]
  [27 28 29]]]
'''

Y2 = X[:, ::2, :]
print(Y1.shape)
print(Y2)
'''
(3, 2, 3)
[[[ 1  2  3]
  [ 7  8  9]]

 [[11 12 13]
  [17 18 19]]

 [[21 22 23]
  [27 28 29]]]
'''

Y3 = X[:, :, ::2]
print(Y1.shape)
print(Y3)
'''
 (3, 3, 2)
[[[ 1  3]
  [ 4  6]
  [ 7  9]]

 [[11 13]
  [14 16]
  [17 19]]

 [[21 23]
  [24 26]
  [27 29]]]
'''

2.2 数组转图片,图片转数组

#-*- coding: utf-8 -*-

# 导入包
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from PIL import Image

#读取图片,并转为数组
im = np.array(Image.open("./images/1.jpg"))

# 打印数组
print(im)

# 隐藏x轴和y轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

# 显示图片
plt.imshow(im)

# #输出图中的最大和最小像素值
print(int(im.min()),int(im.max()))

# 显示图片
plt.show()

2 张量

2.1 生成随机张量

import torch

x = torch.rand(1, 3, 9, 9)

print(x)
print('type(x): ', type(x))
print('x.shape: ', x.shape)

# type(x):  <class 'torch.Tensor'>
# x.shape:  torch.Size([1, 3, 9, 9])

2.2 张量添加维度

img_path = './Images/1.jpg'

img = cv2.imread(img_path)

tran = transforms.ToTensor()
img_tensor = tran(img)
print(img_tensor.size())  # torch.Size([3, 256, 256])

image = torch.unsqueeze(img_tensor, 0)
print(image.size())		# torch.Size([1, 3, 256, 256])

猜你喜欢

转载自blog.csdn.net/everyxing1007/article/details/126881290