matlab张量沿某一维展开,利用numpy整形实现三阶张量展开运算

我尝试在numpython中使用respeme命令对第三级/模式张量执行展开操作。我不确定我所做的是否正确。我在网上找到这篇论文。还找到了以下代码:SVD Image Compression,作者在其中写道:Color images are represented in python as 3 dimensional numpy arrays — the third dimension to represent the color values (red,green blue). However, svd method is applicable to two dimensional matrices. So we have to find a way to convert the 3 dimensional array to 2 dimensional arrays, apply svd and reconstruct it back as a 3 dimensional array. There are two ways to do it. We will show both these methods below.reshape method

Layer method

Reshape method to compress a color image:

This method involves flattening the third dimension of the image array into the second dimension using numpy’s reshape method .

image_reshaped = image.reshape((original_shape[0],original_shape[1]*3))

我试着去理解整形的方法。在我看来,这就像对3阶/模式张量的展开操作。假设我有一个NxMxP大小的数组,如果我使用以下python命令,我将以哪种模式展开:reshape(N, M*P)?在

以下是测试展开操作的方法:import cv2

import numpy as np

def m_unfold(thrd_order_tensor,m):

matrix = []

if m == 1:

matrix = thrd_order_tensor.reshape((thrd_order_tensor.shape[0], thrd_order_tensor.shape[1]*3))

#matrix = np.hstack([thrd_order_tensor[:, :, i] for i in range(thrd_order_tensor.shape[2])])

if m == 2:

matrix = thrd_order_tensor.reshape((thrd_order_tensor.shape[1], thrd_order_tensor.shape[0]*3))

#matrix = np.hstack([thrd_order_tensor[:, :, i].T for i in range(thrd_order_tensor.shape[2])])

if m == 3:

matrix = thrd_order_tensor.reshape((3, thrd_order_tensor.shape[0]*thrd_order_tensor.shape[1]))

#matrix = np.vstack([thrd_order_tensor[:, :, i].ravel() for i in range(thrd_order_tensor.shape[2])])

return matrix

def fold(matrix, os):

#os is the original shape

tensor = matrix.reshape(os)

return tensor

im = cv2.imread('target.jpg')

original_shape = im.shape

image_reshaped = m_unfold(im,3)

U, sig, V = LA.svd(image_reshaped, full_matrices=False)

img_restrd = np.dot(U[:,:], np.dot(np.diag(sig[:]), V[:,:]))

img_restrd = fold(img_restrd,original_shape)

img_restrd = img_restrd.astype(np.uint8)

cv2.imshow('image',img_restrd)

cv2.waitKey(0)

cv2.destroyAllWindows()

你可能感兴趣的:(matlab张量沿某一维展开)