.mat转成.npy文件+Python(Pytorch)压缩裁剪图片
生活随笔
收集整理的這篇文章主要介紹了
.mat转成.npy文件+Python(Pytorch)压缩裁剪图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求:現有數據文件V1.mat,里面包含多個數據集,現需將里面的images數據集提取出來,然后進行壓縮裁剪成指定大小
V1.mat數據集目錄:
1、從mat文件中提取數據(使用Python)
V1.mat文件太大,在此不提供
1 import numpy as np
2 import h5py
3
4 mat = h5py.File('./V1.mat')
5
6 print(mat['images'].shape)#查看mat文件中images的格式
7 #(2284, 3, 640, 480)
8
9 images = np.transpose(mat['images'])
10 #轉置,images是numpy.ndarray格式的
11
12 print(images)#控制臺輸出數據
13 print(images.shape)#輸出數據格式
14 #(480, 640, 3, 2284)
15
16 np.save('./images', images)#保存數據,會生成一個images.npy文件
print(images)輸出的數據:
2、將數據恢復成圖片并保存
1 import numpy as np
2 import torchvision.transforms as transforms
3
4 dataset = np.load('./images.npy')
5
6 for i in range(dataset.shape[3]):
7 img_tensor = dataset[:, :, :, i]#2284
8 # print(img_tensor.shape)#(480, 640, 3)
9
10 img = transforms.ToPILImage()(img_tensor)#轉成圖片
11 # print(img.size)#(640, 480)
12
13 #img.show()
14 img.save('./Test/%d.jpg' % i)
轉成的圖片:
3、壓縮并裁剪圖片
這個程序包含了第二部分,等比例壓縮后再裁剪,可以保持原圖片比例,但會丟失一些邊界信息。直接壓縮可以保存原圖片信息,但會變形。。。
1 import numpy as np
2 import torchvision.transforms as transforms
3 import matplotlib.pyplot as plt
4 from PIL import Image
5
6 dataset = np.load('./V1/images.npy')#圖片文件目錄
7
8
9 '''
10 等比例壓縮
11 '''
12 def scale_high(img, target_high):
13 ow, oh = img.size
14 if (ow == target_high):
15 return img
16 h = target_high
17 w = int(target_high * ow / oh)
18 return img.resize((w, h), Image.BICUBIC)
19
20 '''
21 遍歷圖片
22 等比例壓縮后裁剪
23 '''
24 def ScaleAndCrop():
25 for i in range(1): #dataset.shape[3] #
26 img_tensor = dataset[:, :, :, i] #(480, 640, 3, 2284)
27 #print(img_tensor.shape) #(480, 640, 3)
28 img = transforms.ToPILImage()(img_tensor)#數據轉成圖片
29 # print(img.size) #(640, 480)
30 # img.show()
31 scale_img = scale_high(img,256) #等比例壓縮圖片
32 # print(scale_img.size) #(341, 256)
33 # scale_img.show()
34 crop = transforms.RandomCrop((256, 256)) #裁剪圖片
35 crop_img = crop(scale_img) #
36 # crop_img.show()
37 crop_img.save('./Picture/%d.jpg' % i) #保存圖片
38
39 '''
40 遍歷圖片,直接縮放
41 '''
42 def CropDirc():
43 for i in range(1): #dataset.shape[3] #
44 img_tensor = dataset[:, :, :, i] #(480, 640, 3, 2284)
45 #print(img_tensor.shape) #(480, 640, 3)
46 img = transforms.ToPILImage()(img_tensor)#數據轉成圖片
47 # print(img.size) #(640, 480)
48 # img.show()
49 crop = transforms.Scale([256, 256])
50 crop_img = crop(img)
51
52 # print(crop_img.size) # (256, 256)
53 # crop_img.show()
54 crop_img.save('./Picture/%d.jpg' % i)
總結
以上是生活随笔為你收集整理的.mat转成.npy文件+Python(Pytorch)压缩裁剪图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 看完这个你还不理解右值引用和移动构造 你
- 下一篇: Qt Creator中的3D绘图及动画教