基于LSB替换的空域信息隐藏

########## 返回目录 - 信息隐藏技术(Python) ###
关键点

  1. LSB替换
  2. 字符串与比特流互转
  3. LSB替换之嵌入
  4. LSB替换之提取
  5. 扩展

可改进空间

  1. 提取时可以不需要输入信息长度
  2. 对嵌入的比特流加密
  3. 嵌入的位置可以随机

** 算法问题**

  1. 不可逆
  2. 脆弱、不鲁棒

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) ###

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。