2015-12-22 23 views
-1

我需要帮助来理解下面的代码,我在一个教程解释关于隐写和LSB中找到。然而,我不明白为什么代码编写器使用模运算符(%)。例如,要将新数据插入红色像素中,他使用了% 2,对于绿色% 5等等。代码片段如下:提取最低有效位 - 为什么%操作符是相关的?

for i, x in enumerate(data): 
     if counter < len(message_bit): 
      if i % 2 == 0: 
       r= int(str("{0:b}".format(x[0]))[:-1] + message_bit[counter], 2) # red 
       x = (r, x[1], x[2]) 
       counter += 1 

      elif i % 5 == 0: 
       g = int(str("{0:b}".format(x[1]))[:-1] + message_bit[counter], 2) # green 
       x = (x[0], g, x[2]) 
       counter += 1 

      elif i % 11 == 0: 
       pass 

      else: 
       b = int(str("{0:b}".format(x[2]))[:-1] + message_bit[counter], 2) #blue 
       x = (x[0], x[1], b) 
       counter += 1 

     new_data.append(x) 
+0

我看来像原来的代码是不是位线正好分裂。可能是意图,可能是一个错误。幸运的是,不需要回答他们如何选择常量来回答为什么使用相关操作符的问题。 –

+1

[链接](http://tkmr.hatenablog.com/entry/2014/07/28/223854)到上下文的整个代码。 – Reti43

回答

0

模运算符用于计算整数除法的其余部分。例如,对于递增ii % 3会给出循环结果0,1,2,0,1,2等。常规方法是使用此循环关系将位嵌入到不同的颜色平面中。

if i % 3 == 0: 
    # embed in the red 
elif i % 3 == 1: 
    # embed in the greed 
else: 
    # embed in the blue 

尽管此代码的作者达到了同样的决定,结果显示没有明确的模式和嵌入是不是在所有的颜色平面均匀。

i = 0 
    i % 2 == 0 is true -> embed in RED 
i = 1 
    i % 2 == 0 is false 
    i % 5 == 0 is false 
    i % 11 == 0 is false 
    else     -> embed in BLUE 
i = 2 
    same as i = 0  -> embed in RED 
i = 3 
    same as i = 1  -> embed in BLUE 
i = 4 
    same as i = 0  -> embed in RED 
i = 5 
    i % 2 == 0 is false 
    i % 5 == 0 is true -> embed in GREEN 

continuing with this logic.... 

i = 6     -> embed in RED 
i = 7     -> embed in BLUE 
i = 8     -> embed in RED 
i = 9     -> embed in BLUE 
i = 10     -> embed in RED 
i = 11     -> SKIP 

and so on and so forth 

由于每个其他i都是偶数,所以您会将一半的位嵌入红色。由于i % 5 == 0i % 11 == 0很少是真的,所以你会将大部分余下的位嵌入蓝色。只有大约1/10将进入绿色(具体来说,当i是5,15,25,...)。

我不知道你在哪里找到这段代码,但在我能找到它的唯一地方,海报没有任何解释。所以人们只能猜测这个怪异模式的选择。但是,根据其他代码的质量,我发现作者可能误解了他应该做的事情,这导致了这种奇怪的模式。嵌入和提取例程遵循逻辑的事实意味着程序起作用,作者没有想到过去。

0

提取最低有效位 - 为什么%运算符是相关的?

好,如果你选择一个数字,2^n您将返回至少显著位,这通常是指与bitwise and做了n和口罩如...

m % 4(m % 2**2)将返回至少有意义的2位;在0-3范围内。

这是一样的像m & 3 ...即m & (2**n)-1

+0

虽然你确实回答粗体问题,模运算符的确可以这样使用,但是由于他不了解代码,所以从OP看来这是一个有点令人误解的问题。这里,操作符不是直接用于嵌入/提取,而是作为一个很好的分支,为其执行嵌入的颜色平面。 – Reti43

相关问题