Python实现图像与标签同步随机打乱的方法

Miles
Miles
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍在Python中如何对图像数据集及其对应标签进行同步随机打乱。通过读取训练路径下的图片文件和标签CSV,利用numpy的permutation生成索引序列,确保图片顺序与标签顺序一致。示例代码展示了使用skimage处理图像尺寸及保存打乱后数据的过程,适用于机器学习模型训练前的数据准备阶段。

具体实现方式如下所示:

# -*- coding: utf-8 -*-
 
import os
import numpy as np
import pandas as pd
import h5py
import pylab
import matplotlib.pyplot as plt
 
 
trainpath = str('C:/Users/49691/Desktop/数据集/train/')
testpath = str('C:/Users/49691/Desktop/数据集/test/')
n_tr = len(os.listdir(trainpath))
print('num of training files: ', n_tr)
 
train_labels = pd.read_csv('C:/Users/49691/Desktop/数据集/sample_submission.csv')
train_labels.head()
 
from skimage import io, transform
 
 
x = np.empty(shape=(n_tr, 224, 224, 3))
y = np.empty(n_tr)
 
labels = train_labels.invasive.values
name = train_labels.name.values
 
permutation=np.random.permutation(name.shape[0])
print(permutation)
print(labels[permutation])
save_data = pd.DataFrame({'name':permutation,'invasive':labels[permutation]})
save_data.to_csv('C:/Users/49691/Desktop/数据集/b.csv')
 
 
for k,v in enumerate(np.random.permutation(n_tr)):
 print(k,v)
 path = '{0}{1}.jpg'.format(trainpath, v)
 tr_im = io.imread(path)
 x[k] = transform.resize(tr_im, output_shape=(224, 224, 3))
 y[k] = float(labels[v-1])

以上就是Python中随机打乱图片及其对应标签的完整方法分享,希望能为读者提供有价值的参考,同时也欢迎大家继续支持本站获取更多技术内容。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表