Python:无法重塑numpy.array

时间:2015-10-22 04:02:47

标签: python

我使用LSB在图像中嵌入消息

想法:例如:位中的消息是:01010然后我将全部100 ...到此消息 - >新消息:010101000 ....

这是我的代码:

# 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

    ........

我无法重塑我的msg_img 我希望它的形状像cover_img shape

这是错误:

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

任何人都可以帮助我 提前谢谢!!

1 个答案:

答案 0 :(得分:2)

确定。所以你的重塑不起作用,因为你正在使用reshape()创建一个新的(重塑)数组,然后被遗忘。你需要做的是:

msg_img = msg_img.reshape(cover_img.shape)

或更好:

msg_img.shape = cover_img.shape