如何使用Python OpenCV保存去除黑色背景的图像
原始图像:
预处理后图像:
去除黑色背景并保存的实现方案
要保存无黑色背景的图像,核心是为图像添加Alpha透明通道,将原黑色背景区域标记为透明状态,最终导出为支持透明属性的PNG格式即可(JPG格式不支持透明通道,无法实现该效果)。
可直接运行的修改后完整代码
import cv2 from google.colab.patches import cv2_imshow import numpy as np def rotate_image(image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) return result def rotate_mask(mask, angle): # 单独旋转掩码,保证透明区域和前景对齐 mask_center = tuple(np.array(mask.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(mask_center, angle, 1.0) rotated_mask = cv2.warpAffine(mask, rot_mat, mask.shape[1::-1], flags=cv2.INTER_NEAREST) return rotated_mask img = cv2.imread('/content/52a3b700031458331e469345aaf00f27.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mask = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8) blur = cv2.GaussianBlur(gray, (5,5),0) ret, thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) cv2_imshow(thresh) contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) largest_countour = max(contours, key = cv2.contourArea) # 生成二值掩码,255代表前景保留区域,0代表背景去除区域 binary_mask = cv2.drawContours(mask, [largest_countour], 0, 255, -1) new_img = img * np.dstack((binary_mask/255, binary_mask/255, binary_mask/255)).astype(np.uint8) minRect = cv2.minAreaRect(largest_countour) rotate_angle = minRect[-1] if minRect[-1] < 0 else -minRect[-1] new_img = rotate_image(new_img, rotate_angle) # 同步旋转掩码 rotated_mask = rotate_mask(binary_mask, rotate_angle) # 合并BGR三通道和Alpha透明通道,生成四通道图像 b, g, r = cv2.split(new_img) final_img = cv2.merge((b, g, r, rotated_mask)) # 展示处理结果 cv2_imshow(new_img) # 保存为PNG格式,保留透明背景 cv2.imwrite('/content/no_background_result.png', final_img)
核心修改点说明
- 新增掩码旋转函数,避免旋转后透明区域和前景错位
- 在原有三通道彩色图像基础上新增Alpha通道,掩码对应区域为不透明,原黑色背景区域为完全透明
- 最终导出格式为PNG,完整保留透明属性,保存后的文件可以直接叠加到其他素材上使用,不会带有黑色背景
内容的提问来源于stack exchange,提问作者Med FutureXAI
相关产品推荐
相关产品推荐

