将矩阵列表转换为 Python 中的一个二维矩阵
Convert a list of matrices to only one 2D matrix in Python
我有一个包含 3960 个矩阵的列表,它只是 3960 个图像的 SIFT 描述符。这应该会导致具有未知行数(当然取决于图像)和 128 列(来自 SIFT 描述符)的矩阵列表。我想把这个列表放在一个二维矩阵中,行数是这些矩阵的行数和 128 列的总和,但是,我无法做到这一点。这是我的代码:
sift_keypoints = []
#read images from a text file
with open(file_images) as f:
images_names = f.readlines()
images_names = [a.strip() for a in images_names]
for line in images_names:
print(line)
#read image
image = cv2.imread(line,1)
#Convert to grayscale
image =cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#SIFT extraction
sift = cv2.xfeatures2d.SIFT_create()
kp, descriptors = sift.detectAndCompute(image,None)
#appending sift keypoints to a list
sift_keypoints.append(descriptors)
#here is what I've tried
sift_keypoints = np.asmatrix(np.asarray(sift_keypoints))
根据这段代码,sift_keypoints的形状是(1,3960),这当然不是我想要的。如何将此列表转换为二维 numpy 数组?
编辑 下面代码中的一个简单示例说明了我的问题
#how to convert this list to a matrix with shape (412,128)?
import numpy as np
x=np.zeros((256,128))
y=np.zeros((156,128))
list=[]
list.append(x)
list.append(y)
使用np.concatenate
:
>>> from pprint import pprint
>>> import numpy as np
>>>
>>> a = [np.full((2, 3), i) for i in range(3)]
>>> pprint(a)
[array([[0, 0, 0],
[0, 0, 0]]),
array([[1, 1, 1],
[1, 1, 1]]),
array([[2, 2, 2],
[2, 2, 2]])]
>>> np.concatenate(a, axis=0)
array([[0, 0, 0],
[0, 0, 0],
[1, 1, 1],
[1, 1, 1],
[2, 2, 2],
[2, 2, 2]])
解决方案使用 np.row_stack
假设 l
是形状为 (n, 128)
的 Numpy 数组列表。
假设m
为总行数:对象是将所有对象堆叠起来,创建一个形状为(m, 128)
.
的矩阵
我们可以如下进行,使用Numpy的row_stack
:
result = np.row_stack(l)
我有一个包含 3960 个矩阵的列表,它只是 3960 个图像的 SIFT 描述符。这应该会导致具有未知行数(当然取决于图像)和 128 列(来自 SIFT 描述符)的矩阵列表。我想把这个列表放在一个二维矩阵中,行数是这些矩阵的行数和 128 列的总和,但是,我无法做到这一点。这是我的代码:
sift_keypoints = []
#read images from a text file
with open(file_images) as f:
images_names = f.readlines()
images_names = [a.strip() for a in images_names]
for line in images_names:
print(line)
#read image
image = cv2.imread(line,1)
#Convert to grayscale
image =cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#SIFT extraction
sift = cv2.xfeatures2d.SIFT_create()
kp, descriptors = sift.detectAndCompute(image,None)
#appending sift keypoints to a list
sift_keypoints.append(descriptors)
#here is what I've tried
sift_keypoints = np.asmatrix(np.asarray(sift_keypoints))
根据这段代码,sift_keypoints的形状是(1,3960),这当然不是我想要的。如何将此列表转换为二维 numpy 数组?
编辑 下面代码中的一个简单示例说明了我的问题
#how to convert this list to a matrix with shape (412,128)?
import numpy as np
x=np.zeros((256,128))
y=np.zeros((156,128))
list=[]
list.append(x)
list.append(y)
使用np.concatenate
:
>>> from pprint import pprint
>>> import numpy as np
>>>
>>> a = [np.full((2, 3), i) for i in range(3)]
>>> pprint(a)
[array([[0, 0, 0],
[0, 0, 0]]),
array([[1, 1, 1],
[1, 1, 1]]),
array([[2, 2, 2],
[2, 2, 2]])]
>>> np.concatenate(a, axis=0)
array([[0, 0, 0],
[0, 0, 0],
[1, 1, 1],
[1, 1, 1],
[2, 2, 2],
[2, 2, 2]])
解决方案使用 np.row_stack
假设 l
是形状为 (n, 128)
的 Numpy 数组列表。
假设m
为总行数:对象是将所有对象堆叠起来,创建一个形状为(m, 128)
.
我们可以如下进行,使用Numpy的row_stack
:
result = np.row_stack(l)