【问题标题】:Converting .mat file extension image to .jpg via python通过python将.mat文件扩展名图像转换为.jpg
【发布时间】:2020-03-31 04:42:57
【问题描述】:

我目前正在尝试将图像从 .mat 文件转换为从该站点下载的 .jpg 文件-BrainTumorDataset。 目录下的所有文件都是.mat文件,现在我想通过python将所有.jpg格式的文件转换成一个项目(Brain Tumor Classification using Deep神经网络)通过 CNN。我在谷歌搜索,但我没有从那里得到任何东西,只有一些关于如何在 python 中加载 .mat 文件的主题,但这也对我没有帮助。我在 StackOverflow 中找到了一个answer,但这不适用于这个数据集,而且答案是在 python 中加载 .mat 图像,但我想在 .jpg 中转换 .mat 图像 格式。

【问题讨论】:

  • 那么为什么不加载 .mat 文件并在 for 循环中立即将其打印为 .jpg 呢?
  • 加载 .mat 文件时也出现问题,请尝试使用数据集,我想将文件保存为 .jpg 而不仅仅是打印

标签: python-3.x image matlab image-processing deep-learning


【解决方案1】:

我设法转换了一个图像,使用循环来转换所有图像。

请阅读 cmets。

import matplotlib.pyplot as plt
import numpy as np
import h5py
from PIL import Image

#reading v 7.3 mat file in python
#https://stackoverflow.com/questions/17316880/reading-v-7-3-mat-file-in-python

filepath = '1.mat';
f = h5py.File(filepath, 'r') #Open mat file for reading

#In MATLAB the data is arranged as follows:
#cjdata is a MATLAB struct
#cjdata.image is a matrix of type int16

#Before update: read only image data.   
####################################################################
#Read cjdata struct, get image member and convert numpy ndarray of type float
#image = np.array(f['cjdata'].get('image')).astype(np.float64) #In MATLAB: image = cjdata.image
#f.close()
####################################################################

#Update: Read all elements of cjdata struct
####################################################################
#Read cjdata struct
cjdata = f['cjdata'] #<HDF5 group "/cjdata" (5 members)>

# In MATLAB cjdata = 
# struct with fields:
#   label: 1
#   PID: '100360'
#   image: [512×512 int16]
#   tumorBorder: [38×1 double]
#   tumorMask: [512×512 logical]

#get image member and convert numpy ndarray of type float
image = np.array(cjdata.get('image')).astype(np.float64) #In MATLAB: image = cjdata.image

label = cjdata.get('label')[0,0] #Use [0,0] indexing in order to convert lable to scalar

PID = cjdata.get('PID') # <HDF5 dataset "PID": shape (6, 1), type "<u2">
PID = ''.join(chr(c) for c in PID) #Convert to string https://stackoverflow.com/questions/12036304/loading-hdf5-matlab-strings-into-python

tumorBorder = np.array(cjdata.get('tumorBorder'))[0] #Use [0] indexing - convert from 2D array to 1D array.

tumorMask = np.array(cjdata.get('tumorMask'))

f.close()
####################################################################

#Convert image to uint8 (before saving as jpeg - jpeg doesn't support int16 format).
#Use simple linear conversion: subtract minimum, and divide by range.
#Note: the conversion is not optimal - you should find a better way.
#Multiply by 255 to set values in uint8 range [0, 255], and covert to type uint8.
hi = np.max(image)
lo = np.min(image)
image = (((image - lo)/(hi-lo))*255).astype(np.uint8)

#Save as jpeg
#https://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image
im = Image.fromarray(image)
im.save("1.jpg")

#Display image for testing
imgplot = plt.imshow(image)
plt.show()

注意:
每个mat 文件都包含一个名为cjdata 的结构。
cjdata 结构的字段:

cjdata = 

struct with fields:

      label: 1
        PID: '100360'
      image: [512×512 int16]
tumorBorder: [38×1 double]
  tumorMask: [512×512 logical]

将图像转换为jpeg 时,您会丢失信息...

【讨论】:

  • 它正在工作,但有什么方法可以保留图像的信息,另一个问题是 plt.show() 除了“
    ”没有显示其他图像您的代码可以很好地转换数据并保存为 jpg
  • 另外请添加一个代码来访问'cjdata'的所有元素
  • 添加代码作为第二部分以访问'cjdata'的所有元素,因为当我执行“[key for key in f.keys()]”时它只显示 ['cjdata'] 但我无法访问元素
  • 我更新了我的代码以读取cjdata 的所有元素。 f['cjdata'] 是一个 HDF5 群组,您可以使用get 访问群组成员。解决方案有点混乱,因为在 MATLAB 中,标量存储为 1x1 矩阵,而字符串存储为字符数组...至于图形大小,只是由于绘图参数。
【解决方案2】:

这是使用循环转换所有图像的方法。

from os import path
import os
from matplotlib import pyplot as plt
import numpy as np
import h5py
from PIL import Image
import re
import sys
from glob import glob


dir_path = path.dirname(path.abspath(__file__))
path_to_mat_files = path.join(dir_path, "*.mat")
found_files = glob(path_to_mat_files, recursive=True)
total_files = 0


def convert_to_png(file: str, number: int):
    global total_files
    if path.exists(file):
        print(file, "already exist\nSkipping...")
    else:
        h5_file = h5py.File(file, 'r')
        png = file[:-3] + "png"
        cjdata = h5_file['cjdata']
        image = np.array(cjdata.get('image')).astype(np.float64)
        label = cjdata.get('label')[0,0]
        PID = cjdata.get('PID')
        PID = ''.join(chr(c) for c in PID)
        tumorBorder = np.array(cjdata.get('tumorBorder'))[0]
        tumorMask = np.array(cjdata.get('tumorMask'))
        h5_file.close()
        hi = np.max(image)
        lo = np.min(image)
        image = (((image - lo)/(hi-lo))*255).astype(np.uint8)
        im = Image.fromarray(image)
        im.save(png)
        os.system(f"mv {png} {dir_path}\\png_images")#make sure folder png_images exist
        total_files += 1
        print("saving", png, "File No: ", number)
        
for file in found_files:
    if "cvind.mat" in file:
        continue
    convert_to_png(file, total_files)
print("Finished converting all files: ", total_files)

【讨论】:

  • 我在我的 colab 笔记本中尝试你的代码。它给了我消息 - “完成转换所有文件:0”。我不知道为什么它不起作用。这是我的 colab 笔记本链接:'colab.research.google.com/drive/…'
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多