How do I index a numpy array of zeroes with a boolean datatype to True?

前端 未结 2 840
借酒劲吻你
借酒劲吻你 2021-01-20 17:09

So I\'m recreating a Matlab project they made last year, part of which involves creating mask that pull out the RGB bands. They did this by an array of logical zeroes.

相关标签:
2条回答
  • 2021-01-20 17:50

    numpy can do slicing more or less as in Matlab, but the synax is a little bit different. In numpy, the order is [begin:end:step] and it is possible to leave both begin, end and step empty, which will give them their default values first element, last element and step size 1 respectively.

    Further, `numpy´ has a nice system of 'broad casting' which allows a single value (or row/column) be repeated to make a new array of the same size as another. This makes it possible to assign a single value to a whole array.

    Thus, in the current case, it is possible to do

    self.green_mask_whole=np.zeros((self.rows, self.columns), dtype=bool)
    self.green_mask_whole[::2,1::2] = True
    
    0 讨论(0)
  • 2021-01-20 17:51

    You can translate Matlab's

    GMask_Whole(1:2:end,2:2:end) = true;
    

    to python by

    green_mask_whole[::2,1::2] = True
    

    (assuming green_mask_whole is a numpy array)

    0 讨论(0)
提交回复
热议问题