如何在2D数组中实现逻辑索引以替换循环

时间:2019-03-16 13:00:50

标签: python numpy

更新: 感谢您对高级索引的评论。那就是我想要的。现在,我想为此添加一个额外的维度,并将相同的概念应用于多张图片。

以下是基于2D高级索引的工作原理:

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    Button mainSignInButton = (Button) view.findViewById(R.id.mainSignInButton);
    mainSignInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getActivity() ,LoginActivity.class);
            startActivity(i);
        }
    });

    return view;
}

现在,当我尝试将此概念应用于多张图像时,我必须摆脱一个新的外部for循环。

import numpy as np
img_rows = 8
img_cols = 6
# Initialize image pixels to all zero
img1 = np.zeros(shape=(img_rows, img_cols), dtype='float32')
img2 = np.zeros(shape=(img_rows, img_cols), dtype='float32')

# I have a numpy array of length 'img_cols'
# Each value in the array represents the row index for which I want to set the
#   pixel value of the image in that respective column
row_indices = np.array([4, 2, 7, 0, 3, 6])
# Update the image 1 using a for loop and image 2 using advanced indexing
for i in range(img_cols):
    img1[row_indices[i], i] = 1.0
img2[row_indices, np.arange(len(row_indices))] = 1.0
# Check to verify these are equivalent
print(sum(sum(img1 == img2)) == img_rows * img_cols)

我尝试应用相同的想法,但出现错误:

IndexError:形状不匹配:索引数组无法与形状(2,)(2,6)(6,)一起广播

任何评论将不胜感激。谢谢。

0 个答案:

没有答案