tensor和numpy互相转化

2023-05-16

import torch
import numpy as np

a = np.zeros([2, 2])
print('a\n', a)
# 将numpy类型转换为tensor类型
out = torch.from_numpy(a)
print('out\n', out)
# 将tensor转换为numpy
print('out.numpy\n', out.numpy())

输出结果:

a
 [[0. 0.]
 [0. 0.]]
out
 tensor([[0., 0.],
        [0., 0.]], dtype=torch.float64)
out.numpy
 [[0. 0.]
 [0. 0.]]

读取一张格式为numpy的图片转成tensor

import torch
import numpy as np
import cv2

data = cv2.imread('./test.png')
print('numpy格式\n', data)
# test就是title,即显示在图片的最上边
cv2.imshow('test', data)
# 一定要添加下边这一行否则就执行过去了,就看不到图片了,
# 同时代码也就停到此行不会继续执行下去了,
# 当然如果不想看图片可以不添加
# cv2.waitKey(0)

# 将numpy类型转换为tensor类型
out = torch.from_numpy(data)
print('out\n', out)

执行结果:

numpy格式
 [[[204 204 204]
  [204 204 204]
  [204 204 204]
  ...
  [204 204 204]
  [204 204 204]
  [204 204 204]]

 [[204 204 204]
  [204 204 204]
  [204 204 204]
  ...
  [204 204 204]
  [204 204 204]
  [204 204 204]]

 [[204 204 204]
  [204 204 204]
  [204 204 204]
  ...
  [204 204 204]
  [204 204 204]
  [204 204 204]]

 ...

 [[204 204 204]
  [204 204 204]
  [204 204 204]
  ...
  [204 204 204]
  [204 204 204]
  [204 204 204]]

 [[204 204 204]
  [204 204 204]
  [204 204 204]
  ...
  [204 204 204]
  [204 204 204]
  [204 204 204]]

 [[204 204 204]
  [204 204 204]
  [204 204 204]
  ...
  [204 204 204]
  [204 204 204]
  [204 204 204]]]
out
 tensor([[[204, 204, 204],
         [204, 204, 204],
         [204, 204, 204],
         ...,
         [204, 204, 204],
         [204, 204, 204],
         [204, 204, 204]],

        [[204, 204, 204],
         [204, 204, 204],
         [204, 204, 204],
         ...,
         [204, 204, 204],
         [204, 204, 204],
         [204, 204, 204]],

        [[204, 204, 204],
         [204, 204, 204],
         [204, 204, 204],
         ...,
         [204, 204, 204],
         [204, 204, 204],
         [204, 204, 204]],

        ...,

        [[204, 204, 204],
         [204, 204, 204],
         [204, 204, 204],
         ...,
         [204, 204, 204],
         [204, 204, 204],
         [204, 204, 204]],

        [[204, 204, 204],
         [204, 204, 204],
         [204, 204, 204],
         ...,
         [204, 204, 204],
         [204, 204, 204],
         [204, 204, 204]],

        [[204, 204, 204],
         [204, 204, 204],
         [204, 204, 204],
         ...,
         [204, 204, 204],
         [204, 204, 204],
         [204, 204, 204]]], dtype=torch.uint8)

翻转图片

import torch
import numpy as np
import cv2

data = cv2.imread('./test.png')
print('numpy格式\n', data)
# test就是title,即显示在图片的最上边
cv2.imshow('test', data)
# 一定要添加下边这一行否则就执行过去了,就看不到图片了,
# 同时代码也就停到此行不会继续执行下去了,
# 当然如果不想看图片可以不添加
# cv2.waitKey(0)

# 将numpy类型转换为tensor类型
out = torch.from_numpy(data)
print('out\n', out)
print('*'*50)
# 按照给定的维度翻转张量
out = torch.flip(out, dims=[0])
data = out.numpy()
cv2.imshow('test1', data)
cv2.waitKey(0)

效果

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

tensor和numpy互相转化 的相关文章

随机推荐