【问题标题】:Remake for-loop to numpy broadcast将 for 循环重新制作为 numpy 广播
【发布时间】:2017-02-20 18:48:03
【问题描述】:

我正在尝试通过 numpy 数组编写 LSB 隐写方法。我得到了制作布尔索引掩码的代码,它将给出那些需要与 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 广播

更新: 将我的 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

【问题讨论】:

    标签: python numpy optimization scipy steganography


    【解决方案1】:

    如果您填充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
    

    【讨论】:

    • 我添加了一种无需填充的方法就是使用flat。但是,在这种情况下,您将无法像 np.reshape 给您的那样选择行优先还是列优先。
    猜你喜欢
    • 2017-06-23
    • 2017-12-28
    • 2020-07-09
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多