import matplotlib
matplotlib.use('TkAgg') # 使用交互式后端显示图像
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.ndimage import median_filter
from scipy.signal import convolve2d
import matplotlib.font_manager as fm
# 设置中文字体(确保系统中有这些字体)
try:
font_path = 'C:/Windows/Fonts/msyh.ttc' # 微软雅黑路径
font_prop = fm.FontProperties(fname=font_path)
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei']
plt.rcParams['axes.unicode_minus'] = False
except:
print("警告: 中文显示设置失败,将使用默认字体")
def B_filter(Img, tempsize, sigma0, sigma1):
"""双边滤波函数"""
ksize = 2 * tempsize + 1
ax = np.arange(-tempsize, tempsize + 1, dtype=np.float32)
xx, yy = np.meshgrid(ax, ax)
gauss = np.exp(-(xx ** 2 + yy ** 2) / (2 * sigma0 ** 2))
gauss /= gauss.sum()
m, n = Img.shape
out = Img.copy()
for i in range(tempsize, m - tempsize):
for j in range(tempsize, n - tempsize):
region = Img[i - tempsize:i + tempsize + 1, j - tempsize:j + tempsize + 1]
temp = np.abs(region - Img[i, j])
temp = np.exp(-(temp ** 2) / (2 * sigma1 ** 2))
filter_kernel = gauss * temp
filter_kernel /= filter_kernel.sum()
out[i, j] = np.sum(region * filter_kernel)
return out
def FirstFilter(In):
"""初步过滤函数"""
Out = In.copy()
IR, IG, IB = In[:, :, 0], In[:, :, 1], In[:, :, 2]
mask1 = (IR < 160 / 255) & (IG < 160 / 255) & (IB < 160 / 255) & (IR > IG) & (IG > IB)
mask2 = (IR + IG) > 500 / 255
mask3 = (IR < 70 / 255) & (IG < 40 / 255) & (IB < 20 / 255)
Out[mask1 | mask2 | mask3] = 0
plt.figure(figsize=(10, 6))
plt.imshow(Out)
try:
plt.title('非肤色初步过滤', fontproperties=font_prop)
except:
plt.title('Non-Skin Preliminary Filtering')
plt.axis('off')
plt.show()
return Out
def SecondFilter(In):
"""肤色检测函数"""
IR, IG, IB = In[:, :, 0], In[:, :, 1], In[:, :, 2]
height, width = IR.shape
Out = np.zeros((height, width))
R = IR.flatten()
G = IG.flatten()
B = IB.flatten()
Cg = -81.085 * R + 112 * G - 30.915 * B + 128
Cr = 112 * R - 93.786 * G - 18.214 * B + 128
mask = (Cg >= 85) & (Cg <= 135) & (Cr >= -Cg + 260) & (Cr <= -Cg + 280)
Out.flat[mask] = 1
Out = median_filter(Out, size=3)
plt.figure(figsize=(10, 6))
plt.imshow(Out, cmap='gray')
try:
plt.title('YCgCr空间范围肤色检测', fontproperties=font_prop)
except:
plt.title('Skin Detection in YCgCr Space')
plt.axis('off')
plt.show()
return Out
def Fuse(ImageOrigin, DBImage, SkinArea):
"""图像融合函数"""
Skin = np.stack([SkinArea] * 3, axis=-1)
Out = DBImage * Skin + ImageOrigin * (1 - Skin)
plt.figure(figsize=(10, 6))
plt.imshow(Out)
try:
plt.title('肤色与背景图像融合', fontproperties=font_prop)
except:
plt.title('Skin and Background Fusion')
plt.axis('off')
plt.show()
return Out
def Sharp(In):
"""图像锐化函数"""
In = np.clip(In, 0, 1)
H = np.array([[0, -1, 0],
[-1, 4, -1],
[0, -1, 0]], dtype=np.float32)
sharpened = np.zeros_like(In)
for i in range(3):
sharpened[:, :, i] = convolve2d(In[:, :, i], H, mode='same', boundary='symm')
Out = np.clip(sharpened / 3 + In, 0, 1)
plt.figure(figsize=(10, 6))
plt.imshow(Out)
try:
plt.title('Laplacia锐化图像(最终效果)', fontproperties=font_prop)
except:
plt.title('Sharpened Image (Final Effect)')
plt.axis('off')
plt.show()
return Out
if __name__ == "__main__":
# 读取图像
img_path = 'C:/Users/86155/Desktop/keshe1.webp'
img0 = cv2.imread(img_path)
if img0 is None:
print(f"错误:无法加载图像!请检查文件路径: {img_path}")
exit()
img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)
# 显示原始图像
plt.figure(figsize=(10, 6))
plt.imshow(img0)
try:
plt.title('原图', fontproperties=font_prop)
except:
plt.title('Original Image')
plt.axis('off')
plt.show()
# 参数设置
tempsize = 5
sigma1 = 5
sigma2 = 0.08
# 图像处理流程
img = cv2.copyMakeBorder(img0, tempsize, tempsize, tempsize, tempsize,
cv2.BORDER_CONSTANT, value=0)
img = img.astype(np.float32) / 255.0
# 双边滤波处理
channels = []
for i in range(3):
channel = img[:, :, i].copy()
filtered = B_filter(channel, tempsize, sigma1, sigma2)
channels.append(filtered)
img1 = np.stack(channels, axis=-1)
img1 = img1[tempsize:-tempsize, tempsize:-tempsize, :]
# 显示滤波后图像
plt.figure(figsize=(10, 6))
plt.imshow(img1)
try:
plt.title('高斯滤波处理原图', fontproperties=font_prop)
except:
plt.title('Gaussian Filtered Image')
plt.axis('off')
plt.show()
# 后续处理流程
img2 = img0.astype(np.float32) / 255.0
img3 = FirstFilter(img2)
imgArea = SecondFilter(img3)
imgFuse = Fuse(img2, img1, imgArea)
imgBeautify = Sharp(imgFuse)
# 最终美化处理
imgBeautify_uint8 = (np.clip(imgBeautify, 0, 1) * 255).astype(np.uint8)
imgtmp = cv2.cvtColor(imgBeautify_uint8, cv2.COLOR_RGB2GRAY)
imgtmp = imgtmp.astype(np.float32) / 255.0
imgMB = np.zeros_like(imgBeautify)
for i in range(3):
imgMB[:, :, i] = np.clip(imgBeautify[:, :, i] * 0.9 + imgtmp * 0.2, 0, 1)
# 显示最终结果
plt.figure(figsize=(10, 6))
plt.imshow(imgMB)
try:
plt.title('最终美化效果', fontproperties=font_prop)
except:
plt.title('Final Beautification Result')
plt.axis('off')
plt.show()
print("图像处理流程完成!")
最新发布