两年前做的图还有人点赞甚是高兴,但是ps制作太慢了,现在用代码来实现黑白隐藏图
前置条件
1、python解释器
2、表图,里图
代码
主体代码(保存为1.py)
import cv2
import numpy as np
import os
from tkinter import filedialog
import tkinter as tk
import sys
sys.stdout.reconfigure(encoding='utf-8') # 添加这行来处理中文输出
def create_hidden_image(surface_image_path, hidden_image_path, output_path):
try:
# 读取图片并转换为灰度图
Bimg = cv2.imread(surface_image_path) # 黑色背景显示的图片
Bimg = cv2.cvtColor(Bimg, cv2.COLOR_BGR2GRAY)
# 增强对比度
Bimg = cv2.convertScaleAbs(Bimg, alpha=1.2, beta=0)
Wimg = cv2.imread(hidden_image_path) # 白色背景显示的图片
Wimg = cv2.cvtColor(Wimg, cv2.COLOR_BGR2GRAY)
# 增强对比度
Wimg = cv2.convertScaleAbs(Wimg, alpha=1.2, beta=0)
# 获取两张图片的最小尺寸
h1, w1 = Wimg.shape[:2]
h2, w2 = Bimg.shape[:2]
h = min(h1, h2)
w = min(w1, w2)
# 确保宽高为奇数,以便交错排列
if h % 2 == 0:
h -= 1
if w % 2 == 0:
w -= 1
# 调整图片大小
Wimg = cv2.resize(Wimg, (w, h))
Bimg = cv2.resize(Bimg, (w, h))
# 创建结果图像(BGRA格式,带透明通道)
Rimg = np.zeros([h, w, 4], dtype=np.uint8)
flag = True
# 交错合成两张图片
for y in range(h):
for x in range(w):
if flag:
# 黑色像素:根据灰度值设置透明度
gray = Bimg[y, x]
# 增强黑色效果
alpha = min(255, int(1.2 * (255 - gray))) # 增强透明度对比
Rimg[y, x] = [0, 0, 0, alpha] # 黑色像素,透明度由灰度的反值决定
flag = False
else:
# 白色像素:根据灰度值设置透明度
gray = Wimg[y, x]
# 增强白色效果
alpha = min(255, int(1.2 * gray)) # 增强透明度对比
Rimg[y, x] = [255, 255, 255, alpha] # 白色像素,透明度由灰度决定
flag = True
# 保存结果,使用PNG格式且不压缩
cv2.imwrite(output_path, Rimg, [cv2.IMWRITE_PNG_COMPRESSION, 0])
print(f"合成图片已成功保存到: {output_path}")
return True
except Exception as e:
print(f"发生错误: {str(e)}")
return False
def main():
# 创建tkinter根窗口(但不显示)
root = tk.Tk()
root.withdraw()
print("请选择表图(在黑色背景显示的图片)...")
surface_image_path = filedialog.askopenfilename(title="选择表图",
filetypes=[("图片文件", "*.png *.jpg *.jpeg *.bmp")])
if not surface_image_path:
print("未选择表图,程序退出")
return
print("请选择里图(在白色背景显示的图片)...")
hidden_image_path = filedialog.askopenfilename(title="选择里图",
filetypes=[("图片文件", "*.png *.jpg *.jpeg *.bmp")])
if not hidden_image_path:
print("未选择里图,程序退出")
return
# 默认输出到当前目录,但允许用户选择其他位置
default_output = os.path.join(os.path.dirname(surface_image_path), "结果.png")
output_path = filedialog.asksaveasfilename(title="选择保存位置",
initialfile=default_output,
defaultextension=".png",
filetypes=[("PNG图片", "*.png")])
if not output_path:
print("未选择保存位置,程序退出")
return
if create_hidden_image(surface_image_path, hidden_image_path, output_path):
print("\n处理完成!按回车键退出...")
else:
print("\n处理失败!按回车键退出...")
input()
if __name__ == "__main__":
main()
一键运行(保存为bat文件)
@echo off
python 1.py
pause