基於python的LSB隱寫與分析


隱寫

效果

隱寫前

隱寫后

灰度值直方圖差別

部分源碼

def dec_to_bin(dec):
    return '{:08b}'.format(dec)

def bin_to_dec(binary_code):
    dec = 0
    for i in range(len(binary_code) - 1):
        dec = dec + int(binary_code[i]) * int(pow(2, 7 - i))
    return dec

# 文件信息轉二進制流
def read_data_file(path):
    fp = open(path, "rb")
    stream = ""
    s = fp.read()
    for i in range(len(s)):
        tmp = bin(s[i]).zfill(8)
        stream = stream + tmp.replace('0b', '')
    fp.close()
    return stream

def lsb(image, data_stream, random_index):
    for i in range(len(stream)):
        x = random_index[i] % image.shape[0]
        y = int(random_index[i] / image.shape[0])
        value = image[x, y]
        if value % 2 != stream[i]:
            if value % 2 == 1:
                image[x, y] = value - 1
            else:
                image[x, y] = value + 1
    return image

分析

效果

由於二次隱寫的隨機性,分析圖片存在誤差,但能夠看出是否被隱寫

原圖

隱寫后

部分源碼

# 進行二次隱寫
def random_steg(image, rate):
    pixel_len = image.shape[0] * image.shape[1]
    random_ls = random.sample(range(0, pixel_len), int(pixel_len * rate))
    random_ls.sort()
    for i in random_ls:
        k = random.randint(0, 1)
        x = i % image.shape[0]
        y = int(i / image.shape[0])
        value = image[x, y]
        if not value % 2 == k:
            if value % 2 == 1:
                image[x, y] = value - 1
            else:
                image[x, y] = value + 1
    return image

# 獲取灰度值
def get_gary_value(my_img):
    pixel_value = []
    gary_index = []
    for i in range(256):
        pixel_value.append(0)
        gary_index.append(i)
    for i in range(my_img.shape[0]):
        for j in range(my_img.shape[1]):
            pixel_value[my_img[i][j]] = pixel_value[my_img[i][j]] + 1
    return pixel_value, gary_index

# 計算F1,F2
def calculate_f1f2(values):
    f1 = 0
    f2 = 0
    for i in range(128):
        tmp = abs(values[2 * i + 1] - values[2 * i])
        f1 += tmp
    for j in range(127):
        tmp = abs(values[2 * j + 2] - values[2 * j + 1])
        f2 += tmp
    f2 += abs(values[0] - values[255])
    return f1, f2

# 分析函數
def analysis(path):
    img = cv2.imread(path, 0)
    # 二次隨機隱寫
    F1 = []
    F2 = []
    index = []
    for k in range(11):
        rate = k / 10
        index.append(rate)
        new_img = random_steg(img, rate)
        new_count, new_index = get_gary_value(new_img)
        f_1, f_2 = calculate_f1f2(new_count)
        F1.append(f_1)
        F2.append(f_2)
    draw(F1, F2, index)

相關鏈接

項目鏈接

linzijie1998/lsb_steg_analysis

參考文檔

隱寫與隱寫分析


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM