import numpy as np
from PIL import Image
import os
def Convert():
"""
将图像中白色像素转变为黑色像素
"""
root = 'save_data'
files = [f for f in os.listdir(root)]
print(files)
for filename in files:
img = Image.open(root + '/'+filename)
img = img.convert("RGBA")
pixdata = img.load()
for y in range(img.size[1]):
for x in range(img.size[0]):
if all(pixdata[x,y][i]>220 for i in range(4)):
pixdata[x,y] = 0,0,0
img.save("/ResultData/" + filename)
print("Successfully!"+filename)
if __name__ == "__main__":
Convert()
pass
利用PIL模块对图像中每个像素进行计算,默认三通道中所有像素值都大于220的为白色,将白色像素转为黑色(0,0,0)。