1

I am trying to convert a numpy array of arrays. An example input is this:

np.array([[[0, 0, 0], [255, 255, 255]], [[255, 255, 255], [0, 0, 0]]], np.uint8)

I want to replace all arrays with values [0, 0, 0] with 0 and the [255, 255, 255] with 255. I want the final result to be in this format:

np.array([[0, 255], [255, 0]], np.uint8)

The array will always have the above values but will be different size.

This is the code I created for doing this:

array_list = []
for row in input_image:
    row_list = []
    for item in row:
        if np.array_equal(item, [0, 0, 0]):
            row_list.append(0)
        else:
            row_list.append(255)
    array_list.append(row_list)
output_image = np.array(array_list, np.uint8)

The above code is very slow for big arrays and I was thinking that there might be a way to do this directly with numpy, though I couldn't find a way. Do you have any suggestions for doing this more efficient?

5
  • 1
    What you show to a multi-dimensional array that you want to reduce along the third axis. This is a common operation. However, what do you want to do with other values such as [1, 128, 32], or even [255, 0, 0]? Commented Feb 8, 2020 at 14:33
  • I don't have any other values because I am fixing it with this: input_image = np.where(input_image != 255, 0, input_image) Commented Feb 8, 2020 at 14:35
  • That doesn't guarantee that you don't have say [255, 0, 255] as a value. How do your plan on handling that? Commented Feb 8, 2020 at 14:42
  • If a is the input, you could use a[:, :, 0], or a[..., 0]. Commented Feb 8, 2020 at 14:50
  • Yes, you are right, I didn't thought of that, though it won't be a problem on my application. All I want is to convert some black and white images to masks for OpenCV. Commented Feb 8, 2020 at 14:51

1 Answer 1

2
X_new = np.mean(X, axis=2)
X_new
array([[  0., 255.],
       [255.,   0.]])
Sign up to request clarification or add additional context in comments.

3 Comments

Just take the mean across the third axis. Don't loop with numpy if it's at all avoidable.
And it's always avoidable. The only time I haven't been a able to find a fully vectorized solution was when I wanted to solve multiple simultaneous least squares problems with different coefficients.
@bkbilly Consider to accept the answer as described here stackoverflow.com/help/someone-answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.