将 for 循环重制为 numpy 广播
Remake for-loop to numpy broadcast
我正在尝试通过 numpy 数组对 LSB 隐写术方法进行编码。我得到了制作 bool 索引掩码的代码,它将给出红色通道的那些位,需要与 1 异或。
import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt
message = 'Hello, World!'
message_bits = np.array(map(bool, map(int, (''.join(map('{:b}'.format, bytearray(message)))))), dtype=np.bool)
img = imread('screenshot.png')
xor_mask = np.zeros_like(img, dtype=np.bool)
ind = 0
for j, line in enumerate(xor_mask):
for i, column in enumerate(line):
if ind < len(message_bits):
xor_mask[j, i, 0] = message_bits[ind]
ind += 1
else:
break
else:
continue
break
img[xor_mask] ^= 1
有没有更紧凑的方法来构造xor_mask?也许通过 numpy broadcast
更新:
将我的 for 循环减少为:
for j, line in enumerate(xor_mask):
if ind < len(message_bits):
xor_mask[j, :, 0] = message_bits[ind]
ind += len(xor_mask[j])
else:
break
如果您填充 message_bits
以拥有与 xor_mask
中的像素一样多的元素,那么它就变得简单了:
xor_mask = np.zeros_like(img, dtype=np.bool)
xor_mask[:, :, 0] = np.reshape(message_bits, xor_mask.shape[:2])
另一种方式,没有填充:
xor_mask[:, :, 0].flat[:len(message_bits)] = message_bits
我正在尝试通过 numpy 数组对 LSB 隐写术方法进行编码。我得到了制作 bool 索引掩码的代码,它将给出红色通道的那些位,需要与 1 异或。
import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt
message = 'Hello, World!'
message_bits = np.array(map(bool, map(int, (''.join(map('{:b}'.format, bytearray(message)))))), dtype=np.bool)
img = imread('screenshot.png')
xor_mask = np.zeros_like(img, dtype=np.bool)
ind = 0
for j, line in enumerate(xor_mask):
for i, column in enumerate(line):
if ind < len(message_bits):
xor_mask[j, i, 0] = message_bits[ind]
ind += 1
else:
break
else:
continue
break
img[xor_mask] ^= 1
有没有更紧凑的方法来构造xor_mask?也许通过 numpy broadcast
更新: 将我的 for 循环减少为:
for j, line in enumerate(xor_mask):
if ind < len(message_bits):
xor_mask[j, :, 0] = message_bits[ind]
ind += len(xor_mask[j])
else:
break
如果您填充 message_bits
以拥有与 xor_mask
中的像素一样多的元素,那么它就变得简单了:
xor_mask = np.zeros_like(img, dtype=np.bool)
xor_mask[:, :, 0] = np.reshape(message_bits, xor_mask.shape[:2])
另一种方式,没有填充:
xor_mask[:, :, 0].flat[:len(message_bits)] = message_bits