1

I am attempting to convert a 3 channel numpy array to a single channel numpy array. I want to combine all 3 element values into 1 number using:

x << 16 + y << 8 + z

My code below does that but it seems to make alot of the numbers zero. Is that correct? Or am I doing something wrong? Should those last 2 numbers be zero or something else?

ar = np.array((
    ((255,255,255),),
    ((255,20,255),),
    ((0,255,255),),  # this becomes zero, is that correct? 
    ((22,10,12),),   # this becomes zero, is that correct? 
), dtype='uint8')
c1,c2,c3 = cv2.split(ar)
single = np.int32(c1) << 16 + np.int32(c2) << 8 + np.int32(c3)
print(single)
print(ar.shape)

[[1069547520]
[ 522240]
[ 0]
[ 0]]
(4, 1, 3)

0

1 Answer 1

1

Add a column of zeros to make the array 4 bytes wide:

ar4 = np.insert(ar, 0, 0, 2)

Then simply view it as a big-endian array of 4-byte integers:

ar4.view('>u4')

This gives:

array([[[16777215]],
       [[16717055]],
       [[   65535]],
       [[ 1444364]]], dtype=uint32)

The only step here which really takes time is np.insert(), so if you are able to add that extra column while loading your data, the rest of the transformation is basically free (i.e. does not require copying data).

Sign up to request clarification or add additional context in comments.

Comments

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.