请用python实现LSB实现的图像隐写,要求将一张二值化图像隐写进入24彩色图像中,展现隐写后的图像,然后实现提取过程,提取完成后展现图片
时间: 2024-01-06 16:04:04 浏览: 134
好的,以下是使用Python实现将一张二值化图像隐写进入24彩色图像中并提取的示例代码:
```python
from PIL import Image
def text_to_binary(text):
binary_str = ''.join(format(ord(char), '08b') for char in text)
return binary_str
def binary_to_text(binary_str):
text = ''.join(chr(int(binary_str[i:i+8], 2)) for i in range(0, len(binary_str), 8))
return text
def embed_data(pixel, data):
binary_pixel = list(format(pixel, '08b'))
for i in range(len(data)):
binary_pixel[-1-i] = data[-1-i]
binary_pixel_str = ''.join(binary_pixel)
embedded_pixel = int(binary_pixel_str, 2)
return embedded_pixel
def extract_data(pixel, num_bits):
binary_pixel = list(format(pixel, '08b'))
extracted_data = ''.join(binary_pixel[-num_bits:])
return extracted_data
def embed_image(image_path, data):
image = Image.open(image_path)
if image.mode != 'RGB':
raise ValueError("图像必须是24位彩色图像!")
width, height = image.size
binary_data = text_to_binary(data)
data_len = len(binary_data)
if data_len > width * height:
raise ValueError("二值化图像过大,无法嵌入!")
binary_data += '0' * (width * height - data_len)
data_index = 0
new_pixels = []
for y in range(height):
for x in range(width):
if data_index < data_len:
r, g, b = image.getpixel((x, y))
if binary_data[data_index] == '1':
r |= 1
else:
r &= 254
data_index += 1
if data_index < data_len:
if binary_data[data_index] == '1':
g |= 1
else:
g &= 254
data_index += 1
if data_index < data_len:
if binary_data[data_index] == '1':
b |= 1
else:
b &= 254
data_index += 1
new_pixels.append((r, g, b))
else:
new_pixels.append(image.getpixel((x, y)))
new_image = Image.new(image.mode, image.size)
new_image.putdata(new_pixels)
return new_image
def extract_image(image_path):
image = Image.open(image_path)
if image.mode != 'RGB':
raise ValueError("图像必须是24位彩色图像!")
width, height = image.size
binary_data = ''
for y in range(height):
for x in range(width):
r, g, b = image.getpixel((x, y))
binary_data += str(r & 1)
binary_data += str(g & 1)
binary_data += str(b & 1)
data = binary_to_text(binary_data)
return data
# 嵌入二值化图像
image_path = "24bit_color_image.png"
data_image_path = "binary_image.png"
with Image.open(data_image_path) as data_image:
data_image = data_image.convert('1') # 将图像转换为二值化
data = data_image.tobytes() # 获取二值化图像的二进制数据
new_image = embed_image(image_path, data)
new_image.save("new_image.png")
# 从图像中提取二值化图像
extracted_data = extract_image("new_image.png")
extracted_data_image = Image.frombytes('1', (new_image.width, new_image.height), extracted_data)
extracted_data_image.save("extracted_data_image.png")
```
在上面的示例中,我们将一张二值化图像嵌入到名为`24bit_color_image.png`的24位彩色图像中。首先,我们使用`Pillow`库加载二值化图像,并将其转换为二值图像。然后,我们将二值图像的二进制数据嵌入到24位彩色图像中,并保存嵌入数据后的新图像。接下来,我们从新图像中提取嵌入的二值图像,并将其保存为`extracted_data_image.png`。
请注意,在这个示例中,我们假设二值图像是黑白两色,并且使用`Pillow`库的`convert`函数将其转换为二值图像。如果原始二值图像是灰度图像,可以使用`Pillow`库的`convert('L')`函数将其转换为灰度图像。如果原始二值图像是彩色图像,可以使用`Pillow`库的`convert('RGB')`函数将其转换为24位彩色图像。
阅读全文