Search code examples
opencvimage-processingnumpyregion

NumPy/OpenCV 2: how to enumerate all pixels from region?


This is a continuation of my older question.

Given non-rectangular region, how do I enumerate all pixels from it and arrange them as a single vector? Order doesn't matter (though should be deterministic). Is there any fast way (or at least standard function) or my best approach is iterating over pixels in the image and picking up only those from ROI?

Additional plus if it is possible to restore region data from that vector later.


Solution

  • Extracting the region

    You can use numpy.nonzero()

    mask_1c = mask[:, :, 0]
    indexes = mask_1c.nonzero()
    

    mask_1c is there because in your previous question you have a 3 channel mask image.

    Storing as a vector

    If you'd rather store the content as a single array (instead of a tuple of arrays)

    indexes_v = np.array(indexes).T # Returns an Nx2 matrix
    

    Using the region

    Let's say you then wanted to invert that region, for example:

    image[indexes[0], indexes[1], :] = 255 - image[indexes[0], indexes[1], :]
    

    where I've assumed that the image is of type np.uint8 (has a max of 255).