用python实现LSB隐写与提取

一、LSB在图像中隐写与提取文字

1、隐写

from PIL import Image

"""
取得一个 PIL 图像并且更改所有值为偶数(使最低有效位为 0)
"""


def makeImageEven(image):
    pixels = list(image.getdata())  # 得到一个这样的列表: [(r,g,b,t),(r,g,b,t)...](t表示Alpha通道,显示透明度)
    evenPixels = [(r >> 1 << 1, g >> 1 << 1, b >> 1 << 1, t >> 1 << 1) for [r, g, b, t] in pixels]  # 更改所有值为偶数
    evenImage = Image.new(image.mode, image.size)  # 创建一个相同大小的图片副本
    evenImage.putdata(evenPixels)  # 把上面的像素放入到图片副本
    return evenImage


"""
内置函数 bin() 的替代,返回固定长度的二进制字符串
"""


def constLenBin(int):
    binary = "0" * (8 - (len(bin(int)) - 2)) + bin(int).replace('0b','')  # 去掉 bin() 返回的二进制字符串中的 '0b',并在左边补足 '0' 直到字符串长度为 8
    return binary


"""
将字符串编码到图片中
"""


def encodeDataInImage(image, data):
    evenImage = makeImageEven(image)  # 获得最低有效位为 0 的图片副本
    binary = ''.join(map(constLenBin, bytearray(data, 'utf-8')))  # 将需要被隐藏的字符串转换成二进制字符串
    #print(binary)
    #print(len(binary))
    if len(binary) > len(image.getdata()) * 4:  # 如果不可能编码全部数据, 抛出异常
        raise Exception("Error: Can't encode more than " + len(evenImage.getdata()) * 4 + " bits in this image. ")
    encodedPixels = [(r + int(binary[index * 4 + 0]), g + int(binary[index * 4 + 1]), b + int(binary[index * 4 + 2]),
                      t + int(binary[index * 4 + 3])) if index * 4 < len(binary) else (r, g, b, t) for
                     index, (r, g, b, t) in enumerate(list(evenImage.getdata()))]  # 将 binary 中的二进制字符串信息编码进像素里
    concealedImage = Image.new(evenImage.mode, evenImage.size)  # 创建新图片以存放编码后的像素
    concealedImage.putdata(encodedPixels)  # 添加编码后的数据
    return concealedImage



if  __name__ == "__main__":
    encodeDataInImage(Image.open("coffee.png"), 'PEACE TO THE WORLD').save('concealedImage.png')

载体图像:

图片说明

隐写文字:PEACE TO THE WORLD

生成图像:

图片说明

2、提取

from PIL import Image


"""
从二进制字符串转为 UTF-8 字符串
"""

def binaryToString(binary):
    index = 0
    string = []
    rec = lambda x, i: x[2:8] + (rec(x[8:], i - 1) if i > 1 else '') if x else ''
    # rec = lambda x, i: x and (x[2:8] + (i > 1 and rec(x[8:], i-1) or '')) or ''
    fun = lambda x, i: x[i + 1:8] + rec(x[8:], i - 1)
    while index + 1 < len(binary):
        chartype = binary[index:].index('0')  # 存放字符所占字节数,一个字节的字符会存为 0
        length = chartype * 8 if chartype else 8
        string.append(chr(int(fun(binary[index:index + length], chartype), 2)))
        index += length
    return ''.join(string)


"""
解码隐藏数据
"""

def decodeImage(image):
    pixels = list(image.getdata())  # 获得像素列表
    binary = ''.join([str(int(r >> 1 << 1 != r)) + str(int(g >> 1 << 1 != g)) + str(int(b >> 1 << 1 != b)) + str(
        int(t >> 1 << 1 != t)) for (r, g, b, t) in pixels])  # 提取图片中所有最低有效位中的数据
    #print(binary)
    #print(len(binary))
    # 找到数据截止处的索引
    locationDoubleNull = binary.find('0000000000000000')
    endIndex = locationDoubleNull + (
                8 - (locationDoubleNull % 8)) if locationDoubleNull % 8 != 0 else locationDoubleNull
    data = binaryToString(binary[0:endIndex])
    return data

if __name__ == "__main__":
    print(decodeImage(Image.open("concealedImage.png")))

执行结果

图片说明

二、LSB在图像中隐写与提取二值文字图像

1、隐写

from PIL import Image


"""
取得一个 载体图像并且更改所有值为偶数(使最低有效位为 0)
"""

def makeImageEven(image):
    pixels = list(image.getdata())  # 得到一个这样的列表: [(r,g,b,t),(r,g,b,t)...]
    evenPixels = [(r >> 1 << 1, g >> 1 << 1, b >> 1 << 1, t >> 1 << 1) for [r, g, b, t] in pixels]  # 使最低有效位为0
    evenImage = Image.new(image.mode, image.size)  # 创建一个相同大小的图片副本
    evenImage.putdata(evenPixels)  # 把上面的像素放入到图片副本
    return evenImage


"""
二值化文字图像
"""

def BinarizationImage(img):

    Img = img.convert('L')

    # 自定义灰度界限,大于这个值为黑色,小于这个值为白色
    threshold = 200

    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)

    # 图片二值化

    photo = Img.point(table, '1')
    photo.save("test.png")
    pixels = list(photo.getdata())

    #print(pixels)
    #print(len(pixels))

    return pixels

"""
将二值列表转换为二值字符串
"""

def constLenBin(int):

    binary = bin(int).replace('0b','')  # 去掉 bin() 返回的二进制字符串中的 '0b'
    return binary


"""
将二值文字图像编码到图片中
"""

def encodeDataInImage(image, img):
    evenImage = makeImageEven(image)  # 获得最低有效位为 0 的图片副本
    BinarizationImage(img)
    binary = ''.join(map(constLenBin, BinarizationImage(img)))  #将图像二进制列表转换成二进制字符串

    #print(binary)
    #print(len(binary))

    if len(binary) % 4 != 0:
        binary = binary + "0"*(((len(binary)//4)+1)*4 - len(binary))

    #print(binary)
    #print(len(binary))

    if len(binary) > len(image.getdata()) * 4:  # 如果不可能编码全部数据, 抛出异常
        raise Exception("Error: Can't encode more than " + len(evenImage.getdata()) * 4 + " bits in this image. ")

    encodedPixels = [(r + int(binary[index * 4 + 0]), g + int(binary[index * 4 + 1]), b + int(binary[index * 4 + 2]),
                      t + int(binary[index * 4 + 3])) if index * 4 < len(binary)
                      else (r, g, b, t) for index, (r, g, b, t) in enumerate(list(evenImage.getdata()))]

    #print(encodedPixels)

    encodedImage = Image.new(evenImage.mode, evenImage.size)  # 创建新图片以存放编码后的像素
    encodedImage.putdata(encodedPixels)  # 添加编码后的数据
    return encodedImage



if  __name__ == "__main__":
    encodeDataInImage(Image.open("coffee.png"), Image.open("secret.png")).save('encodeImage.png')

隐写二值文字图像:

图片说明

生成图像:

图片说明

2、提取

from PIL import Image

"""
解码隐藏数据
"""

def decodeImage(image,img):
    pixels = list(image.getdata())  # 获得像素列表
    binary = ''.join([str(int(r >> 1 << 1 != r)) + str(int(g >> 1 << 1 != g)) + str(int(b >> 1 << 1 != b)) + str(
        int(t >> 1 << 1 != t)) for (r, g, b, t) in pixels])  # 提取图片中所有最低有效位中的数据

    #print(binary)

    # 找到数据截止处的索引
    decodeImage = Image.new(img.mode, img.size)  # 创建新图片以存放编码后的像素
    endIndex = img.size[0]*img.size[1]
    binary = binary[0:endIndex]

    #print(binary)
    #print(len(binary))

    #将二值字符串转为像素列表
    pixels=[]
    for i in binary:
        j = int(i)
        if j == 1:
            k = 255
        else: k = 0
        pixels.append(k)

    #print(pixels)

    decodeImage.putdata(pixels)  # 添加编码后的数据
    return decodeImage


if __name__ == "__main__":
    decodeImage(Image.open("encodeImage.png"),Image.open("secret.png")).save('decodeImage.png')

提取结果:

图片说明

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:29
点赞 评论 收藏
分享
06-22 10:41
赣东学院 Java
程序员小白条:?周六晚上投,这是什么操作,专门找996起步的吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务