python将图片中某种颜色修改为其他颜色
def replace_color_in_images1(directory, old_color, threshold, new_color):
'''
将目录中所有图片中的某种颜色替换为其他颜色
:param directory: 图片所在目录
:param old_color: 要替换的颜色
:param threshold: 颜色阈值
:param new_color: 替换后的颜色
'''
old_r, old_g, old_b = old_color
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".png"):
img_path = os.path.join(directory, filename)
img = Image.open(img_path)
data = img.load()
for y in range(img.size[1]):
for x in range(img.size[0]):
r, g, b = data[x, y]
if abs(r - old_r) < threshold and abs(g - old_g) < threshold and abs(b - old_b) < threshold:
data[x, y] = new_color
img.save(img_path)
# 使用示例
replace_color_in_images1("images", (0, 0, 0), 10, (0, 0, 255))
版权所有,转载时必须以链接形式注明原始出处