Skip to content

Instantly share code, notes, and snippets.

@xiaoland
Created August 10, 2025 15:46
Show Gist options
  • Select an option

  • Save xiaoland/f3f49a0fbf427a41ca18e18565e2b340 to your computer and use it in GitHub Desktop.

Select an option

Save xiaoland/f3f49a0fbf427a41ca18e18565e2b340 to your computer and use it in GitHub Desktop.
Python Script for remove image bg by diff
import cv2
import numpy as np
def subtract_image(original_path, mask_path, output_path):
# 读取原图(BGR)与扣好图(尽量保留Alpha)
original = cv2.imread(original_path, cv2.IMREAD_COLOR)
mask_img = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED)
if original is None or mask_img is None:
print("Error: One or both images could not be read.")
return
# 尺寸对齐(如不同则缩放mask)
if original.shape[:2] != mask_img.shape[:2]:
mask_img = cv2.resize(
mask_img, (original.shape[1], original.shape[0]),
interpolation=cv2.INTER_NEAREST
)
# 生成二值Alpha掩码(优先用扣图的Alpha通道)
if mask_img.ndim == 3 and mask_img.shape[2] == 4:
alpha = mask_img[:, :, 3]
else:
gray_mask = cv2.cvtColor(mask_img, cv2.COLOR_BGR2GRAY)
_, alpha = cv2.threshold(gray_mask, 1, 255, cv2.THRESH_BINARY)
# 用掩码提取RGB并合成RGBA
rgb_masked = cv2.bitwise_and(original, original, mask=alpha)
b, g, r = cv2.split(rgb_masked)
rgba = cv2.merge([b, g, r, alpha])
# 确保以PNG保存以支持透明
if not output_path.lower().endswith(".png"):
output_path = output_path.rsplit(".", 1)[0] + ".png"
cv2.imwrite(output_path, rgba)
print(f"Result saved to {output_path}")
# 示例用法
original_path = r'' # 替换为原图的路径
mask_path = r'' # 替换为扣好的图片的路径
output_path = r'' # 替换为你希望保存结果的路径
subtract_image(original_path, mask_path, output_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment