| import numpy as np |
| import cv2 |
| |
| |
| def encode(s, width=8): |
| bin_str = ''.join([(bin(c).replace('0b', '')).zfill(width) for c in s.encode(encoding="utf-8")]) |
| return bin_str |
| |
| |
| def decode(s): |
| s = [np.uint8(c) for c in s] |
| bin_str = ''.join([bin(b & 1).strip('0b').zfill(1) for b in s]) |
| str = np.zeros(np.int(len(s) / 8)).astype(np.int) |
| for i in range(0, len(str)): |
| str[i] = int('0b' + bin_str[(8 * i):(8 * (i + 1))], 2) |
| return bytes(str.astype(np.int8)).decode() |
| |
| |
| def lsb_embed(img, s): |
| if len(img.shape) == 3: |
| |
| width, height, channel = img.shape |
| s = encode(s) |
| for i in range(len(s)): |
| x = i // width |
| y = i % width |
| channel = i // (height * width) |
| value = img[x, y, channel] |
| if (value % 2) == int(s[i]): |
| pass |
| if (value % 2) > int(s[i]): |
| img[x, y, channel] = value - 1 |
| if (value % 2) < int(s[i]): |
| img[x, y, channel] = value + 1 |
| else: |
| width, height = img.shape |
| s = encode(s) |
| for i in range(len(s)): |
| x = i // width |
| y = i % width |
| value = img[x, y] |
| if (value % 2) == int(s[i]): |
| pass |
| if (value % 2) > int(s[i]): |
| img[x, y] = value - 1 |
| if (value % 2) < int(s[i]): |
| img[x, y] = value + 1 |
| return img, len(s) |
| |
| |
| def lsb_extract(img, num): |
| if len(img.shape) == 3: |
| |
| width, height, channel = img.shape |
| s = '' |
| for i in range(num): |
| x = i // width |
| y = i % width |
| channel = i // (height * width) |
| value = img[x, y, channel] |
| if value % 2 == 0: |
| s += '0' |
| else: |
| s += '1' |
| else: |
| width, height = img.shape |
| s = '' |
| for i in range(num): |
| x = i // width |
| y = i % width |
| value = img[x, y] |
| if value % 2 == 0: |
| s += '0' |
| else: |
| s += '1' |
| return decode(s) |
| |
| |
| if __name__ == '__main__': |
| |
| msg = "hello world" |
| pic_origin = cv2.imread('lenna.bmp') |
| pic_embed, msg_len = lsb_embed(pic_origin, msg) |
| cv2.imwrite('pic_embed.bmp', pic_embed) |
| |
| pic_embed = cv2.imread('pic_embed.bmp') |
| msg_extract = lsb_extract(pic_embed, msg_len) |
| print(msg_extract) |