0

Basically I'd like to implement 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. 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)
kapits
  • 59
  • 1
  • 8
  • 1
    Possible duplicate of [python assign values to list elements in loop](https://stackoverflow.com/questions/20688324/python-assign-values-to-list-elements-in-loop) – MB-F Mar 22 '18 at 15:31

1 Answers1

0

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. With numpy one usually tries to push as many loops as possible into the numpy data types.

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()
BlackJack
  • 4,476
  • 1
  • 20
  • 25