I have a numpy array ys_big_seg
which has the following shape: (146, 128, 128). It contains pixel masks which values can be 0 or 1. 1 if the pixel is in a given category otherwise 0. I have to scale it to binary mask. So I want to iterate through the (128, 128) matrices and split it to (8, 8) matrices and then based on the smaller matrices values (if every element is 0 then 0, if every element is 1 then 1, if there are mixed values then randomly 0 or 1) substitute these smaller matrices with given values to reduce the (128, 128) matrices to (16, 16).
How can I solve this problem? I hope it makes sense, sorry for my English.
CodePudding user response:
I think this does what you're looking for:
>>> x.shape
(146, 128, 128)
>>> mask = x.reshape(-1, 16, 16, 8, 8).sum(axis=(3, 4)) >= 32
>>> mask.shape
(146, 16, 16)
Any 8x8 block with a mixture of 0s and 1s will result in a 1 if the total sum is >= 32 (i.e., half or more of the values values are 1), so it's not quite randomly chosen.
Obviously, a sum of 0 (all elements in an 8x8 block are 0) will "fail" that criteria and be 0, and a sum of 64 (all elements in an 8x8 block are 1) will "pass" and end up as a 1. If your matrices are a lot more sparse, you could lower the threshold from 32
.
Since you're using this array as a mask, you can leave the 1s and 0s as their boolean counterparts. But if you plan to use the mask as a binary array, then you can easily add .astype(int)
.