user5154523
user5154523

Reputation:

Python: Can not reshape numpy.array

Im using LSB to embed a message in an image

Idea: for example: message in bit is: 01010 then i will all 100... to this message -> new message: 010101000....

Here is my code:

# num_lsbs: number of bits replaced: 1bit or 2bits, ...
# cover_image_file: original image
# stego_image_file: image file after embeded

def lsb(cover_img_file, msg_file, num_lsbs, stego_image_file):
    #1. Read cover_img_file 
    cover_img = imread(cover_img_file) # cover_img: numpy 

    #2.1 Read msg_file
    file_obj = open(msg_file, 'r')
    msg = file_obj.read()
    file_obj.close()

    #2.2 Conver msg to msg_bits
    msg_bits = bitarray.bitarray()
    msg_bits.fromstring(msg)

    #2.3 Add 100... to msg bit
    max_num_bits = num_lsbs * cover_img.size 
    # Check if there are enough spaces
    if (len(msg_bits) > max_num_bits - 1):
        print "Not enough spaces to embed"
        return

    msg_bits.extend('1' + '0' * (max_num_bits - len(msg_bits) - 1)) 

    #2.4 Convert msg_bits to msg img
    str01 = msg_bits.to01()

    msg_img = np.array ([int(str01[i:i + num_lsbs], 2) for i in range (0, len(msg_bits),
                                                               num_lsbs)], dtype = np.uint8)
    msg_img.reshape(cover_img.shape)
    print '\n\n--------Check shape--------\n'
    print cover_img.shape, cover_img.dtype
    print msg_img.shape, msg_img.dtype

              ^
              |
              |
        #<<I can not reshape here>>
    #3. Embed msg img to cover img
    stego_img = ((cover_img >> num_lsbs) << num_lsbs) + msg_img

    ........

I can not reshape my msg_img I want its shape is like cover_img shape

Here is the error:

<ipython-input-2-82ce863f48cb> in embed_lsb(cover_img_file, msg_file, num_lsbs, stego_image_file)
     41 
     42     #3. Embed msg img to cover img
---> 43     stego_img = ((cover_img >> num_lsbs) << num_lsbs) + msg_img
     44 
     45     #4. Save the stego img file

ValueError: operands could not be broadcast together with shapes (414,500,3) (621000,) 

Can anyone help me Thank in advance!!

Upvotes: 1

Views: 1077

Answers (1)

Julien
Julien

Reputation: 15071

Ok. So your reshaping didn't work because you are using reshape() which creates a new (reshaped) array, which is then forgotten. What you need to do is:

msg_img = msg_img.reshape(cover_img.shape)

or better:

msg_img.shape = cover_img.shape

Upvotes: 2

Related Questions