简体   繁体   English

如何在Python中正确实现二进制对称通道?

[英]How to implement Binary Symmetric Channel in Python correctly?

Basically I'd like to implement BSC. 基本上我想实现BSC。 A photo is changed into bits, some of them are changed and a new image is created. 将照片更改为位,其中一些位被更改并创建新图像。 The issue I encountered is that I get the same image back. 我遇到的问题是我得到了相同的图像。 I've put some print() statements to see if the error() works and it looks like it does. 我放置了一些print()语句以查看error()是否有效,并且看起来确实可行。 Here's my code: 这是我的代码:

import numpy as np
import random as rand

# Seed

rand.seed(4)

# Filenames
in_name = 'in_img.png'
out_name = 'out_img.png'

# Into bits
in_bytes = np.fromfile(in_name, dtype="uint8")
in_bits = np.unpackbits(in_bytes)
data = list(in_bits)



# BSC

def error(x):
    p = 0.1
    is_wrong = rand.random() < p
    if is_wrong:
        if x == 1:
            return 0
        else:
            return 1
    else:
        return x


for i in data:
    i = error(i)

# To PNG
out_bits = np.array(data)
out_bytes = np.packbits(out_bits)
out_bytes.tofile(out_name)

While the problem in your code seems to be a duplicate as kazemakase points out in a comment, your code should not use such a loop and a Python list in the first place. 正如kazemakase在注释中指出的那样,虽然您的代码中的问题似乎是重复的,但您的代码首先不应使用这样的循环和Python list With numpy one usually tries to push as many loops as possible into the numpy data types. 使用numpy通常会尝试将尽可能多的循环推入numpy数据类型。

import numpy as np


def main():
    np.random.seed(4)

    in_name = 'in_img.png'
    out_name = 'out_img.png'

    bits = np.unpackbits(np.fromfile(in_name, np.uint8))
    bits ^= np.random.random(bits.shape) < 0.1
    np.packbits(bits).tofile(out_name)


if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM