当前位置: 首页 > 工具软件 > PTL > 使用案例 >

018-PTL库在图像预处理中的使用

羊禄
2023-12-01

018-PTL库在图像预处理中的使用

#Reading images
from PIL import Image 
 
  
img = Image.open("images/test_image.jpg") #Not a numpy array
print(type(img)) #输出<class 'PIL.PngImagePlugin.PngImageFile'> 相当于它的类别
# 在外部默认查看器上显示图像。这可以是Windows上的绘画或照片查看器
img.show() 

print(img.format) # 本机输出结果为 PNG 表示图片的格式是png格式的
#打印模式的图像RGB或CMYK
print(img.mode)  #输出结果为RGBA

print(img.size) #(1874, 914)


# Resize images
small_img = img.resize((200, 300))
small_img.save("images/test_image_small.jpg") 


#方法将图片大小调整为精确的值,不管是否合理。
#没有保持高宽比,所以图像被压缩。
#如果你想保持方面的比例,那么使用thumbnai()方法

img.thumbnail((200, 200))# 可以保持图片的大小比值
img.save("images/test_image_small_new.jpg")


cropped_img = img.crop((0, 0, 300, 300))  #将图片剪裁成(0,0) to (300,300)


img2.thumbnail((200, 200))  #resize成一个比较大的size. 

img1_copy = img1.copy()   #创建成一个copy
img1_copy.paste(img2, (50, 50))  #img1粘贴到img2上 img2的size要比img1的大
img1_copy.save("images/pasted_image.jpg")


img_90_rot = img.rotate(90)
img_90_rot.save("images/rotated90.jpg") #将图片旋转90度,会将超出边界的信息剪切掉



img_45_rot = img.rotate(45, expand=True)#旋转45度并会随着图片的尺寸大小而变化
img_90_rot.save("images/rotated90.jpg")


img_flipLR = img.transpose(Image.FLIP_LEFT_RIGHT)#对图片进行转置
img_flipLR.save("images/flippedLR.jpg")



grey_img = img.convert('L')  #L 将图片转为灰度图
grey_img.save("images/grey_img.jpg")


#######################################################################################
读取整个文件夹的图片并保存

from PIL import Image 
import glob

path = "images/test_images/aeroplane/*.*"
for file in glob.glob(path):
    print(file)     #just stop here to see all file names printed
    a= Image.open(file)  #现在,我们可以读取每个文件,因为我们有完整的路径
    
    rotated45 = a.rotate(45, expand=True)
    rotated45.save(file+"_rotated45.png", "PNG")   

 

 类似资料: