修改参数:
1.original_folder:需要为图像添加掩膜的原始文件夹地址
2.new_folder:添加掩膜后图像的保存文件夹地址
import os
import cv2
import random
if __name__ == '__main__':
# 原始文件夹路径
original_folder = r'C:\Users\12302\Desktop\demo_one'
# 保存的新文件夹路径
new_folder = r'C:\Users\12302\Desktop\demo_two'
for filename in os.listdir(original_folder):
img = cv2.imread(os.path.join(original_folder, filename),cv2.IMREAD_COLOR)
img_copy = img.copy()
mask_height = img.shape[0] // 10
mask_width = img.shape[1] // 10
for index in range(10):
x = random.randint(0, img.shape[1] - mask_width)
y = random.randint(0, img.shape[0] - mask_height)
img_copy[y:y + mask_height, x:x + mask_width] = 0
cv2.imwrite(os.path.join(new_folder, filename), img_copy, [int(cv2.IMWRITE_PNG_COMPRESSION), 5])
修改前:
修改后: