gpt4 book ai didi

Python:无法 reshape numpy.array

转载 作者:行者123 更新时间:2023-12-01 04:24:50 27 4
gpt4 key购买 nike

我使用 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

........

我无法 reshape 我的 msg_img我希望它的形状像 cover_img 形状

这是错误:

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

谁能帮帮我提前致谢!!

最佳答案

好的。因此,您的 reshape 不起作用,因为您正在使用 reshape() ,它创建了一个新的( reshape 的)数组,然后该数组被遗忘了。您需要做的是:

msg_img = msg_img.reshape(cover_img.shape)

或更好:

msg_img.shape = cover_img.shape

关于Python:无法 reshape numpy.array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33273222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com