########## 返回目录 - 信息隐藏技术(Python) ###
关键点:
- LSB替换
- 字符串与比特流互转
- LSB替换之嵌入
- LSB替换之提取
- 扩展
可改进空间
- 提取时可以不需要输入信息长度
- 对嵌入的比特流加密
- 嵌入的位置可以随机
** 算法问题**
- 不可逆
- 脆弱、不鲁棒
import cv2
import numpy as np
import matplotlib.pyplot as plt
import random
def getBit(num, bit_idx=8):
''' From num, get the given bit specified by bit_idx
'''
return (num & (1<<(8-bit_idx))) >> (8-bit_idx)
def setBit(num, bit, bit_idx=8):
''' For num, set the given bit specified by bit_idx
'''
num -= getBit(num, bit_idx)<<(8-bit_idx)
num += (bit <<(8-bit_idx))
return num
def str2bitseq(s, width=8):
'''
Input: s: character string
Output: bit array in np.uint8
'''
binstr = ''. join([(bin(c).replace('0b', '')).zfill(width) for c in s.encode(encoding="utf-8")])
bitseq = [np.uint8(c) for c in binstr]
return bitseq
def bitseq2str(msgbits):
'''
Input: bit array in np.uint8
Output: s: character string
'''
binstr = ''.join([bin(b & 1).strip('0b').zfill(1) for b in msgbits])
str = np.zeros(np.int(len(msgbits)/8)).astype(np.int)
for i in range(0, len(str)):
str[i] = int('0b'+ binstr[(8*i):(8*(i+1))], 2)
return bytes(str.astype(np.int8)).decode()
if __name__ == '__main__':
img_file = './monarch.png'
img_gray = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)
# bit0 = getBit(img_gray[0,0], 8)
# print(img_gray[0,0], bit0)
# num0 = img_gray[0,0]
# num1 = setBit(num0, 0, 8)
# print(num0, num1)
# msg = '图像dsfjk算术运算mon'
# bin_s0 = str2bitseq(msg)
# msg1 = bitseq2str(bin_s0)
# print(len(bin_s0), bin_s0)
# print(msg, '--', msg1)
msg = '图像算jdghjyuon术运算masgh'
bin_s0 = str2bitseq(msg)
height, width = img_gray.shape
# embedding
cnt = 0
for i in np.arange(height):
if cnt > len(bin_s0):
break
for j in np.arange(width):
if cnt >= len(bin_s0):
break
bit = bin_s0[cnt]
cnt += 1
img_gray[i, j] = setBit(img_gray[i, j], bit, 8)
cv2.imwrite('monarch_lsb.png', img_gray)
# Extraction
img_marked = cv2.imread('monarch_lsb.png', cv2.IMREAD_GRAYSCALE)
bin_s1 = []
cnt = 0
for i in np.arange(height):
if cnt > len(bin_s0):
break
for j in np.arange(width):
if cnt >= len(bin_s0):
break
bin_s1.append(getBit(img_marked[i, j], 8))
cnt += 1
msg_out = bitseq2str(bin_s1)
print(msg, ' -- ', msg_out)
plt.figure()
plt.subplot(121), plt.imshow(img_gray, cmap='gray')
plt.subplot(122), plt.imshow(img_marked, cmap='gray')
plt.tight_layout()
plt.show()
结果
图像算jdghjyuon术运算masgh -- 图像算jdghjyuon术运算masgh
########## 返回目录 - 信息隐藏技术(Python) ###