Question

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.

Was it helpful?

Solution 2

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).

OTHER TIPS

You can use numpy.where() function for this. You don't have to do iterate through the pixels.

I will continue from your last question. In the accepted answer, a mask is created and you have drawn a polygon on it, to decide the mask region. What you have to do is to simply find where pixel is 255 in that mask image.

ROI_pixel_locations = np.transpose(np.where(mask[:,:,0]==255))

This will give you a Mx2 array of x,y locations.

If you are using OpenCV 2.4.4 or higher, it has a function cv2.nonzero() with exactly same purpose.

NOTE :

In the previous question, the accepted answer creates 3 channel mask image. If it was a single channel mask image, you need to give only like this :

ROI_pixel_locations = np.transpose(np.where(mask==255))

But during AND operation, you modify line as follows :

masked_image = cv2.bitwise_and(image,image, mask=mask)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top