python h5文件读取_python读取整个txt文件

python h5文件读取_python读取整个txt文件这篇文章是一个工具类,用来辅助医学图像分割实战unet实现(二)4、数据存储这一小节的内容。文件:HDF5DatasetGenerator.py#-*-coding:utf-8-*-importh5pyimportosimportnumpyasnpclassHDF5DatasetGenerator:def__init__(self,…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

这篇文章是一个工具类,用来辅助医学图像分割实战 unet实现(二) 4、数据存储 这一小节的内容。

2019/5/2 更新:HDF5DatasetWrite可以动态扩展储存大小

文件: HDF5DatasetGenerator.py

# -*- coding: utf-8 -*-
import h5py
import os
import numpy as np

class HDF5DatasetGenerator:
    
    def __init__(self, dbPath, batchSize, preprocessors=None,
                 aug=None, binarize=True, classes=2):
        self.batchSize = batchSize
        self.preprocessors = preprocessors
        self.aug = aug
        self.binarize = binarize
        self.classes = classes
        
        self.db = h5py.File(dbPath)
        self.numImages = self.db["images"].shape[0]
# self.numImages = total
        print("total images:",self.numImages)
        self.num_batches_per_epoch = int((self.numImages-1)/batchSize) + 1
        
    
    def generator(self, shuffle=True, passes=np.inf):
        epochs = 0
        
        while epochs < passes:
            shuffle_indices = np.arange(self.numImages) 
            shuffle_indices = np.random.permutation(shuffle_indices)
            for batch_num in range(self.num_batches_per_epoch):
                
                start_index = batch_num * self.batchSize
                end_index = min((batch_num + 1) * self.batchSize, self.numImages)
                
                # h5py get item by index,参数为list,而且必须是增序
                batch_indices = sorted(list(shuffle_indices[start_index:end_index]))
                
                images = self.db["images"][batch_indices,:,:,:]
                labels = self.db["masks"][batch_indices,:,:,:]
                
# if self.binarize:
# labels = np_utils.to_categorical(labels, self.classes)
                
                if self.preprocessors is not None:
                    procImages = []
                    for image in images:
                        for p in self.preprocessors:
                            image = p.preprocess(image)
                        procImages.append(image)
                    
                    images = np.array(procImages)
                
                if self.aug is not None:
                    # 不知道意义何在?本身images就有batchsize个了
                    (images, labels) = next(self.aug.flow(images, labels,
                                                        batch_size=self.batchSize))
                yield (images, labels)
            
            epochs += 1
            
    def close(self):
        self.db.close()

文件: HDF5DatasetWriter.py

# -*- coding: utf-8 -*-
import h5py
import os

class HDF5DatasetWriter:
    def __init__(self, image_dims, mask_dims, outputPath, bufSize=200):
        """ Args: - bufSize: 当内存储存了bufSize个数据时,就需要flush到外存 """
        if os.path.exists(outputPath):
            raise ValueError("The supplied 'outputPath' already"
                             "exists and cannot be overwritten. Manually delete"
                             "the file before continuing", outputPath)
        
        self.db = h5py.File(outputPath, "w")
        self.data = self.db.create_dataset("images", image_dims, maxshape=(None,)+image_dims[1:], dtype="float")
        self.masks = self.db.create_dataset("masks", mask_dims, maxshape=(None,)+mask_dims[1:], dtype="int")
        self.dims = image_dims
        self.bufSize = bufSize
        self.buffer = { 
   "data": [], "masks": []}
        self.idx = 0
    

    def add(self, rows, masks):
        # extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
        # 注意,用extend还有好处,添加的数据不会是之前list的引用!!
        self.buffer["data"].extend(rows)
        self.buffer["masks"].extend(masks)
        print("len ",len(self.buffer["data"]))
        
        if len(self.buffer["data"]) >= self.bufSize:
            self.flush()
    
    def flush(self):
        i = self.idx + len(self.buffer["data"])
        if i>self.data.shape[0]:
        	# 扩展大小的策略可以自定义
            new_shape = (self.data.shape[0]*2,)+self.dims[1:]
            print("resize to new_shape:",new_shape)
            self.data.resize(new_shape)
            self.masks.resize(new_shape)
        self.data[self.idx:i,:,:,:] = self.buffer["data"]
        self.masks[self.idx:i,:,:,:] = self.buffer["masks"]
        print("h5py have writen %d data"%i)
        self.idx = i
        self.buffer = { 
   "data": [], "masks": []}
        
    
    def close(self):
        if len(self.buffer["data"]) > 0:
            self.flush()
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/197612.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Ubuntu更换Linux内核版本

    Ubuntu更换Linux内核版本Ubuntu14 04 5 默认 Linux 内核版本号是 4 4 0 31 这几天为了换一个低版本的内核 在网上查了蛮多帖子 最后虽然有点小问题 切换内核版本不是很方便 但总算是勉强更换成功 试了几个方法不行后 按照 nbsp https blog csdn net xin yu xin article details nbsp 这篇帖子的方法成功更换 博主的步骤基本没问题 我是一步一步对照着进行的

    2025年7月24日
    2
  • TLD(Tracking-Learning-Detection)一种目标跟踪算法

    TLD(Tracking-Learning-Detection)一种目标跟踪算法原文:http://blog.csdn.net/mysniper11/article/details/8726649视频介绍网址:http://www.cvchina.info/2011/04/05

    2022年8月5日
    8
  • 如何画好业务架构图图片_产品业务流程图怎么画

    如何画好业务架构图图片_产品业务流程图怎么画1:什么是业务架构图描述系统对用户提供了什么业务功能。业务架构图是一种表达业务层级和关系的工具。业务架构图可以降低业务系统的复杂度,提高客户理解度,最终给客户最直观的业务体现。2:怎么画出一个好的业务架构图呢?2.1:熟悉功能必须要对功能特别熟悉,明白自己的软件的业务都有哪些,哪些是核心业务,哪些是边缘业务以及他们之间的关系是什么。2.2:分层将业务进行分层,一般来说上层是具体业务,下层比较抽象。下层为上层进行提供服务。在业务架构图中,上下要进行对齐,体现出它们的支持关系。2.3分功能

    2022年10月11日
    3
  • 【19】进大厂必须掌握的面试题-50个React面试

    【19】进大厂必须掌握的面试题-50个React面试

    2020年11月13日
    211
  • oracle import/export 命令[通俗易懂]

    oracle import/export 命令[通俗易懂]exp/imp实例   exphelp=y查看帮助exp1、expusr/pwd@sid file=c:\tb.dump tables=tb1  如果是导出多个表,tables=(tb1、tb2)2、expusr/pwd@sid file=c:\tb.dump –全部导出3、expusr/pwd@sid file=c:\tb.dump owne

    2025年9月11日
    10
  • 什么是MVC软件架构模式_mvc架构的设计思路

    什么是MVC软件架构模式_mvc架构的设计思路缘起:作为程序员,很容易天天被业务追逐着,抽不开时间修炼。有一天突然停了一下,忽地就会有一种怅然的感觉,过去的那些日子我学到了什么?有人很认真地说自己有10年经验,有人笑说你不过是一年经验用了10年而已。

    2022年10月10日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号