和跟老师做的项目,需要用到多种类型的图片的转换,将10000张图片(含pgm类型)转换为JPG、png、bmp类型的各一万张,看了老师推荐的博客,c#处理pgm。哎老实说,根本看不懂啊。就用了最简单的方式,用Python实现。
不知道以后看到这个简单的代码会不会发笑哈哈哈
1>转换
import os
from PIL import Image
import sys
def get_imlist(path):
return[os.path.join(path,f) for f in os.listdir(path)]
directory1=get_imlist('/home/winney/images/bmp/')
directory2=get_imlist('/home/winney/images/jpg/')
directory3=get_imlist('/home/winney/images/pgm/')
#directory3=get_imlist('/home/winney/images/Photex_pgm/VosskuhlerCCD1300LN_pgm/')
directory4=get_imlist('/home/winney/images/png/')
counter=0
for directory in [directory1,directory2,directory3,directory4]:
for in_image in directory:
try:
img=Image.open(in_image)
counter=counter+1
out_image1=str(counter)+".jpg"
out_image2=str(counter)+".png"
out_image3=str(counter)+".bmp"
to_save1="/home/winney/original_image/"+out_image1
to_save2="/home/winney/original_image/"+out_image2
to_save3="/home/winney/original_image/"+out_image3
img.save(to_save1)
img.save(to_save2)
img.save(to_save3)
except Exception,e:
print e,in_image
"""for directory in [directory1,directory2,directory3,directory4]:
if not os.access(directory,os.F_OK):
print directory,"isn't a valid directory !"
sys.exit()
print "Directory",directory
for in_image in os.walk(directory):
out_image=os.path.splitext(in_image)[0]+".jpg"
#in_image=os.path
#out_image=in_image[0:in_image.find(".")+1]+"jpg"
try:
Image.open(in_image).save("/home/winney/original_image/"+out_image)
except IOError:
print "cannot convert",in_image"""
2>统计
import os
from PIL import Image
import sys
def get_imlist(path):
return[os.path.join(path,f) for f in os.listdir(path) if f.endswith('.pgm')]
def get_imlist(path):
return[os.path.join(path,f) for f in os.listdir(path)]
directory=get_imlist('/home/winney/original_image')
counter1=0
counter2=0
counter3=0
for in_image in directory:
if in_image.endswith('.jpg'):
counter1=counter1+1
elif in_image.endswith('png'):
counter2=counter2+1
elif in_image.endswith('bmp'):
counter3=counter3+1
print counter1,' ',counter2,' ',counter3