【python\numpy】用python处理适用于存储 [细胞分割PanNuke数据集] 的npy文件 || 代码合集

【start:20231104】

简介

在使用Python进行数据处理和科学计算时,我们经常会遇到需要读取或写入npy文件的情况。npy文件是NumPy库中用于存储多维数组数据的二进制文件格式,它能够高效地保存和加载大规模的数组数据。

npy文件基础

import library

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

make and save npy file

# make and save npy file

# 创建一个示例列表
data_list = [1, 2, 3, 4, 5]
# 将列表转换为DataFrame
df = pd.DataFrame(data_list, columns=['Data'])
# 将DataFrame转换回NumPy数组
data_array = df.to_numpy()
# 将NumPy数组保存为.npy文件
np.save('data_array.npy', data_array)

load npy file

# load npy file

# 加载npy文件
data_array = np.load('data_array.npy')
# 将数据转换为Pandas DataFrame
df = pd.DataFrame(data_array)
# 打印DataFrame
print(df)

np.dtype问题

参考资料

【ref】如何将深度学习的float32图像转为Unit8格式以方便cv2使用

涉及到np.dtype问题时,应该注意什么?

在处理NumPy数据类型(np.dtype)时,特别是在涉及不同的数据类型(如uint8float64等)时,你需要注意以下几点:

  1. 数据范围和精度: 不同的数据类型具有不同的值范围和精度。例如,uint8表示无符号8位整数,范围为0到255,而float64表示双精度浮点数,具有更高的精度但占用更多的内存空间。确保选择适当的数据类型来存储你的数据,以避免数据丢失或溢出的问题。

  2. 内存占用: 数据类型不同会影响所占用的内存空间。例如,uint8通常占用比float64更少的内存空间。在处理大型数据集时,选择适当的数据类型可以减少内存占用,提高程序的性能。

  3. 计算和操作: 不同的数据类型在进行数学运算和操作时会表现出不同的行为。某些数据类型可能不支持特定的操作或会导致精度损失。在进行计算之前,了解所使用的数据类型以及其行为特性是很重要的。

  4. 数据转换: 在数据处理过程中,可能需要进行数据类型的转换。要注意数据转换可能会导致精度损失或数据溢出。确保在进行数据类型转换时选择合适的方法,以保持数据的完整性和准确性。

  5. 存储和读取: 在存储和读取数据时,确保使用正确的数据类型。选择适当的数据类型可以确保数据的完整性并减少存储和读取过程中的错误。

通过了解不同数据类型的特点和使用场景,你可以更好地管理数据,并确保在处理数据时不会出现潜在的问题和错误。

float32和uint8数据类型互转

float32uint8是常见的NumPy数据类型,它们具有不同的数据范围和精度。下面是它们各自的数据范围:

  • float32: 它是32位浮点数类型,通常用于表示单精度浮点数(用于表示 0 到 1的带有小数部分的实数)。它可以表示大约 7 个有效数字,并具有较高的精度。其值范围约为 − 3.4 × 1 0 38 到 3.4 × 1 0 38 -3.4 × 10^{38} 到 3.4 × 10^{38} 3.4×10383.4×1038

  • uint8: 它是8位无符号整数类型,用于表示 0 到 255 之间的整数。它通常用于表示像素值等在 0 到 255 之间的数据,例如图像数据中的灰度值或颜色通道值。

在进行数据转换时,要注意数据范围的差异。转换时确保数据不会溢出或丢失精度。对于float32uint8的转换,你需要将float32数据乘以 255 并进行取整操作以保持在 0 到 255 之间的 uint8 范围内。而对于uint8float32的转换,你需要将uint8数据除以 255 以保持在 0 到 1 之间的范围内;下面是两个示例:

  1. float32uint8的转换:
import numpy as np

# 创建一个示例的float32类型数组
float_array = np.array([0.1, 0.5, 0.9], dtype=np.float32)

# 将float32类型数组转换为uint8类型数组
uint8_array = (float_array * 255).astype(np.uint8)
print("uint8 array:", uint8_array)
  1. uint8float32的转换:
import numpy as np

# 创建一个示例的uint8类型数组
uint8_array = np.array([50, 100, 200], dtype=np.uint8)

# 将uint8类型数组转换为float32类型数组
float_array = uint8_array.astype(np.float32) / 255
print("float32 array:", float_array)

在这两个示例中,我们分别将float32类型的数组转换为uint8类型的数组以及将uint8类型的数组转换为float32类型的数组。通过在astype()方法中指定目标数据类型,你可以实现不同数据类型之间的转换。

npy文件用于处理image和mask

example dataset(PanNuke)

以处理PanNuke数据集为例

【dataset link】PanNuke dataset download

J. Gamper, N. A. Koohbanani, K. Benes, S. Graham, M. Jahanifar, S. A. Khurram, A. Azam, K. Hewitt, and N. Rajpoot, “PanNuke Dataset Extension, Insights and Baselines,” arXiv preprint arXiv:2003.10778, 2020.

image class type(一维数组:N)

## image_type (一维数组:N)

path = "/home/linxq/dataset/cell/pannuke/Fold 3/images/fold3/types.npy"

# 从.npy文件中加载数据
data = np.load(path)
print(data.shape)

# 将数据转换为Pandas DataFrame
df = pd.DataFrame(data)
# 打印DataFrame
print(df)

在这里插入图片描述

image(四维数组3通道:N, 256, 256, 3)

# image (四维数组3通道:N, 256, 256, 3)

path_image = "/home/linxq/dataset/cell/pannuke/Fold 3/images/fold3/images.npy"

# 从.npy文件中加载数据
data_image = np.load(path_image)
print(data_image.shape)

# 数据归一化
data_image_normalized = data_image.astype('float32') / 255.0

# 选择要展示的图像数量
num_images_to_show = 5
# 从data_normalized中随机选择五张图像
random_indices = np.random.choice(len(data_image_normalized), num_images_to_show, replace=False)
print('random_indices: ', random_indices)
# 创建子图
fig, axes = plt.subplots(1, num_images_to_show, figsize=(15, 3))
# 展示随机选择的图像
for i, idx in enumerate(random_indices):
    axes[i].imshow(data_image_normalized[idx])
    axes[i].axis('off')  # 关闭坐标轴
plt.show()

在这里插入图片描述

image pixel Distribution hist(分布图)

# image pixel Distribution hist

def draw_hist(data, data_name):
    
    plt.hist(data.flatten(), bins=50, color='b', alpha=0.7, rwidth=0.85)
    
    title_name = 'Pixel Distribution ' + data_name

    plt.title(title_name)
    plt.xlabel('Pixel Value')
    plt.ylabel('Percentage')
    plt.grid(axis='y', alpha=0.75)

path = "/home/linxq/dataset/cell/pannuke/Fold 3/images/fold3/images.npy"

# 从.npy文件中加载数据
data = np.load(path)
print(data.shape)

# 数据归一化
data_normalized = data.astype('float32') / 255.0

plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
# 绘制原始数据的像素分布百分比图
draw_hist(data, 'data')
plt.subplot(1, 2, 2)
# # 绘制归一化数据的像素分布百分比图
draw_hist(data_normalized, 'data_normalized')
plt.tight_layout()
plt.show()

效果:
在这里插入图片描述

mask(四维数组6通道:N, 256, 256, 6)

# mask (四维数组6通道:N, 256, 256, 6)

path_mask = "/home/linxq/dataset/cell/pannuke/Fold 3/masks/fold3/masks.npy"
# 从.npy文件中加载数据
data_mask = np.load(path_mask)
print(data_mask.shape)

# 选择要展示的图像数量
num_images_to_show = 5
# 从data中随机选择五个样本
random_indices = np.random.choice(data_mask.shape[0], num_images_to_show, replace=False)
# 创建子图
fig, axes = plt.subplots(num_images_to_show, 6, figsize=(15, 3*num_images_to_show))
# 展示随机选择的图像
for i, idx in enumerate(random_indices):
    for j in range(6):
        axes[i, j].imshow(data_mask[idx, :, :, j])
        axes[i, j].axis('off')  # 关闭坐标轴
plt.tight_layout()
plt.show()

在这里插入图片描述

image+mask(多分类问题)

# image+mask

import numpy as np
import matplotlib.pyplot as plt

# 原始图像路径
path_image = "/home/linxq/dataset/cell/pannuke/Fold 3/images/fold3/images.npy"
# 从.npy文件中加载数据
data_image = np.load(path_image)
print("Image data shape:", data_image.shape)

# 图像数据归一化
data_image_normalized = data_image.astype('float32') / 255.0

# 掩膜图像路径
path_mask = "/home/linxq/dataset/cell/pannuke/Fold 3/masks/fold3/masks.npy"
# 从.npy文件中加载数据
data_mask = np.load(path_mask)
print("Mask data shape:", data_mask.shape)

# 选择要展示的图像数量
num_images_to_show = 3

# 从原始图像数据中随机选择五张图像
random_indices = np.random.choice(len(data_image_normalized), num_images_to_show, replace=False)

# 创建子图
fig, axes = plt.subplots(num_images_to_show, 7, figsize=(18, 3*num_images_to_show))

# 展示随机选择的图像和对应的掩膜图像
for i, idx in enumerate(random_indices):
    # 展示原始图像
    axes[i, 0].imshow(data_image_normalized[idx])
    axes[i, 0].axis('off')  # 关闭坐标轴

    # 展示各个掩膜图像
    for j in range(6):
        axes[i, j + 1].imshow(data_mask[idx, :, :, j])
        axes[i, j + 1].axis('off')  # 关闭坐标轴
plt.tight_layout()
plt.show()

在这里插入图片描述

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以的,以下是Python代码载入stl10数据集的训练集和测试集,并保存为npy文件的示例: ``` import numpy as np import os import urllib.request import tarfile from PIL import Image def download_data(): url = 'http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz' if not os.path.isfile('stl10_binary.tar.gz'): urllib.request.urlretrieve(url, 'stl10_binary.tar.gz') if not os.path.isdir('stl10_binary'): with tarfile.open('stl10_binary.tar.gz') as tar: tar.extractall() def read_data(split): path = 'stl10_binary' if split == 'train': filename = os.path.join(path, 'train_X.bin') with open(filename, 'rb') as f: X_train = np.fromfile(f, dtype=np.uint8) X_train = np.reshape(X_train, (-1,3,96,96)) X_train = np.transpose(X_train, (0,3,2,1)) filename = os.path.join(path, 'train_y.bin') with open(filename, 'rb') as f: y_train = np.fromfile(f, dtype=np.uint8) return X_train, y_train elif split == 'test': filename = os.path.join(path, 'test_X.bin') with open(filename, 'rb') as f: X_test = np.fromfile(f, dtype=np.uint8) X_test = np.reshape(X_test, (-1,3,96,96)) X_test = np.transpose(X_test, (0,3,2,1)) filename = os.path.join(path, 'test_y.bin') with open(filename, 'rb') as f: y_test = np.fromfile(f, dtype=np.uint8) return X_test, y_test def save_data(X, y, filename): np.save(filename, {'X': X, 'y': y}) if __name__ == '__main__': download_data() X_train, y_train = read_data('train') X_test, y_test = read_data('test') save_data(X_train, y_train, 'train.npy') save_data(X_test, y_test, 'test.npy') ``` 这段代码会首先下载STL10数据集的压缩文件,然后解压出训练集和测试集的图像和标签,并转换为numpy数组的格式,并将其保存为npy文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值