Python图像处理:使用pickle存储和读取图像数据

这篇文章介绍如何使用Python的OpenCV和pickle库来处理图像数据。我们将学习如何将图像转换为数组、存储在pickle文件中,以及如何从文件中加载数据并显示图像。pythonimport osimport cv2import numpy as npimport pandas as pdimport pickleimport matplotlib.pyplot as plt

定义图像路径和文件路径img_path = 'dataul/testul/test'img_path2= 'dataul/testul.pickle'file_path= 'dataul/csvul/test.csv'

读取标签信息imglist_file = pd.read_csv(file_path)

定义批次标签batch_label='cancer images'

初始化变量index = 0k = 1labels = []filename_list = []num = 0imgs = np.empty(27648,)

循环遍历图像文件夹for i in os.listdir(img_path): # 读取图像 path = os.path.join(img_path, i) img = cv2.imread(path) # 调整图像大小 img = cv2.resize(img, (96, 96)) img = np.array(img)

# 分离颜色通道并将数组扁平化    b, g, r = cv2.split(img)    img_array = np.concatenate((r, g, b), axis=0)    array1 = img_array.flatten()

# 将图像数据和标签存储到数组中    imgs = np.vstack([imgs,array1])            labels.append(imglist_file['label'][num])    num = num +1

删除初始化数组的第一行imgs = np.delete(imgs,0,axis=0)

打印数组信息print(labels)print(len(labels))print(imgs)print(imgs.shape)

将数据保存到pickle文件d_decoded = {}with open(img_path2, 'wb+') as f: d_decoded[b'batch_label'] = batch_label d_decoded[b'labels'] = labels d_decoded[b'data'] = imgs d_decoded[b'filenames'] = filename_list pickle.dump(d_decoded, f)

从pickle文件加载数据with open(img_path2, 'rb') as f: model = pickle.load(f, encoding='bytes')

# 转换数据并显示图像    imges_batch = np.array(model[b'data'])    images = imges_batch.reshape([-1, 3, 96, 96])

imgs = images[0, :, :, :].reshape([3, 96, 96])    img = np.stack((imgs[0, :, :], imgs[1, :, :], imgs[2, :, :]), 2)    plt.imshow(img)    plt.show()

代码解释:

  1. 导入库: 导入必要的库,包括os, cv2, numpy, pandas, pickle, 和 matplotlib.pyplot。2. 定义路径和变量: 定义图像路径、文件路径、批次标签以及其他变量。3. 读取数据: 使用pandas读取csv文件中的标签信息。4. 循环处理图像: 遍历图像文件夹,读取每个图像,调整大小,分离颜色通道,并将图像数据存储在数组中。5. 存储数据: 使用pickle将图像数据和标签存储在pickle文件中。6. 加载数据: 使用pickle从文件中加载数据。7. 显示图像: 将加载的图像数据转换为数组,并使用matplotlib.pyplot显示图像。

这段代码提供了一个简单的例子,演示了如何使用Python处理图像数据,并使用pickle文件进行存储和加载。 这对于需要处理大量图像数据的机器学习项目非常有用。

Python图像处理:使用pickle存储和读取图像数据

原文地址: https://www.cveoy.top/t/topic/f1KP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录