批量将读取图片并进行二值化处理,并以txt形式保存在指定文件夹
#代码
import os
from PIL import Image
def init(fileList,n):
for i in range(0,n):
img = Image.open(imagepath + str(fileList[i]))
w,h=img.size
img = img.convert('1')
list_img_name = []
path_imgs = imagepath
for files in os.listdir(path_imgs):
img_path = files.rstrip('.jpg')
list_img_name.append(img_path)
with open(txtpath+str(list_img_name[i])+".txt", "w") as f:
for c in range(h):
for j in range(w):
f.write(str(int((255-(img.getpixel((j,c))))/255)))
if j==w-1:
f.write("\n")
f.close()
if __name__=="__main__":
fileList=os.listdir(imagepath)
n=len(fileList)
init(fileList,n)
#注释
#其中imagepath为读取的图片路径,txtpath保存txt文件的路径。`在这里插入代码片`由于PIL只支持python2版本,若不能运行,安装pillow库可同样适用。