[英]Convert a list of matrices to only one 2D matrix in Python
我有一个3960矩阵的列表,它只是3960图像的SIFT描述符。 据推测,这将导致矩阵列表的行数未知(当然,行数取决于图像)和128列(来自SIFT描述符)。 我试图将此列表仅放在一个2D矩阵中,行数是这些矩阵和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.row_stack
解决方案 假设l
是您的形状为(n, 128)
的Numpy数组的列表。
假设m
是总行数:对象是堆叠所有对象并创建形状为(m, 128)
的矩阵。
我们可以使用Numpy的row_stack
进行以下row_stack
:
result = np.row_stack(l)
使用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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.