抠像 原图 和 标签合并,查看抠像是否准确
合并后的图,是带有 羽化 效果的
import os
import cv2
import numpy as np
def apply_mask_with_feathering(original_image_path, mask_image_path):
# 读取原图和mask图
original_image = cv2.imread(original_image_path)
mask_image = cv2.imread(mask_image_path, cv2.IMREAD_GRAYSCALE)
# 检查两个图像的尺寸是否匹配
if original_image.shape[:2] != mask_image.shape[:2]:
raise ValueError("The dimensions of the original image and the mask image do not match.")
# 创建一个带有标签的图像
labeled_image = original_image.copy()
# 将mask图归一化到0到1之间
mask_float = mask_image.astype(float) / 255.0
# 创建标签颜色
label_color = np.array([0, 0, 255], dtype=float) # BGR格式,红色
# 将标签颜色应用到原图上,同时保留羽化效果
for c in range(3): # 对每个颜色通道进行处理
labeled_image[:, :, c] = labeled_image[:, :, c] * (1 - mask_float) + label_color[c] * mask_float
return original_image, labeled_image
if __name__ == '__main__':
jpg_path = r'C:\Users\hzy\Desktop\1111\20240517'
png_path = r'C:\Users\hzy\Desktop\1111\20240517_syl'
output_image_path = r'C:\Users\hzy\Desktop\1111\labeled'
for root, dirs, files in os.walk(jpg_path):
for file in files:
filename, ext = os.path.splitext(file)
if ext not in ['.png', '.jpg']:
continue
jpg = os.path.join(root, file)
png = os.path.join(png_path, filename + '.png')
# 使用示例
original_image, labeled_image = apply_mask_with_feathering(jpg, png)
# 显示原图和带标签的图像
cv2.imshow(file, original_image)
cv2.imshow("Labeled Image", labeled_image)
# 等待用户按键按下
cv2.waitKey(0)
cv2.destroyAllWindows()
output_img_path = os.path.join(output_image_path, file)
# 保存结果图像
cv2.imwrite(output_img_path, labeled_image)
效果:
原图
标签图
合并后的图