简体   繁体   English

避免for循环迭代Python中的数组

[英]Avoiding for loop to iterate over an array in Python

I am a beginner in Python, trying to implement computer vision algorithms.I have to iterate over image read as a 2 dimensional array several times and I want to avoid using for loops. 我是Python的初学者,尝试实现计算机视觉算法。我必须对读取为二维数组的图像进行多次迭代,并且要避免使用for循环。

For example, I want to multiply camera matrix P(3x4 dimension) with each row of coordinate matrix, where each row is dimension 1x4. 例如,我想将相机矩阵P(3x4尺寸)与坐标矩阵的每一行相乘,其中每一行的尺寸为1x4。 I will of course take transpose of the row vector for matrix multiplication. 我当然会把行向量转置为矩阵乘法。 Here is how I have implemented it using for loop. 这是我使用for循环实现它的方式。 I initialize an empty array. 我初始化一个空数组。 Cameras is an object instance. 相机是一个对象实例。 So I loop over the object to find the total number of cameras. 因此,我遍历对象以查找摄像机总数。 Counter gives me the total number of cameras. 计数器给了我相机的总数。 Then I read through each row of matrix v_h and perform the multiplication. 然后,我通读矩阵v_h的每一行并执行乘法。 I would like to accomplish the below task without using for loop in python. 我想在不使用for循环的情况下完成以下任务。 I believe it's possible but I don't know how to do it. 我相信这是可能的,但我不知道该怎么做。 For the number of points in thousands, using for loop is becoming very inefficient. 对于成千上万的点数,使用for循环变得非常低效。 I know my code is very inefficient and would appreciate any help. 我知道我的代码效率很低,将不胜感激。

   for c in cameras:
     counter=counter+1

   for c in cameras:       
     v_to_s=np.zeros((v_h.shape[0],c.P.shape[0],counter),dtype=float)
     for i in range(0,v_h.shape[0]):
       v_to_s[i,:,cam_count]=np.dot(c.P,v_h[i,:].T)

numpy具有可以执行乘法的matmul()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM