np transpose

本文通过实例展示了NumPy库中数组转置与重塑的基本操作。包括二维和三维数组的转置方法,并通过图像数据进一步说明了这些操作在实际应用中的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试np中数组的转置操作:

# coding=gbk
'''
Created on 2017年5月9日

'''
from scipy.misc.pilutil import * # read image 
import matplotlib.pyplot as plt   # show image 

import numpy as np # 两个方法都用

from numpy import *


###############################################
################## 二维数组 ######################
arr = np.array([[1,2,3],[4,5,6]])
rows = arr.shape[0]
cols = arr.shape[1]

print "rows: ", rows,"cols: ",cols
# test python.numpy: rows major
arr2 = np.reshape(arr,[1,arr.shape[0]*arr.shape[1]])

print arr2 # result: [1 2 3 4 5 6]
################### 三维数组 ###########################
arr_3d = np.array([[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]],[[17,18,19,20],[21,22,23,24]]])

print arr_3d.shape # (3L,2L,4L)  (页,行,列),按行存储
## reshpae 
arr_3d_reshape = arr_3d.reshape((1,arr_3d.shape[0]*arr_3d.shape[1]*arr_3d.shape[2]))
print arr_3d_reshape # (1,24)

arr_3d_tran = arr_3d.transpose((2,1,0)) 

arr_3d_tran_reshape = arr_3d_tran.reshape((1,arr_3d.shape[0]*arr_3d.shape[1]*arr_3d.shape[2]))

print "arr_3d_tran_reshape : ",arr_3d_tran_reshape
print arr_3d_tran.shape #(4L,2L,3L)
print arr_3d_tran
print arr_3d
######################### 分析结果 #####################
##########    
##########
#######################################################


######## 分析图像
img = imread("lena.jpg")

######################
print img.shape # (512L,512L,3L)
print type(img.shape) # tuple
########################

img_tran1 = img.transpose((2,1,0)) # change (0,1,2) to (2,1,0)

print img_tran1.shape #(3L,512L,512L)

gray_img = img[:,:,0]


plt.subplot(1,2,1)
plt.imshow(gray_img)
plt.subplot(1,2,2)
plt.imshow(img_tran1[0,:,:])
plt.show()

# 结论: 由 (512,513,3),即 高*宽*通道,转换为 :(3,512,512),即 通道*宽*高

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值