如何在Python中从原始图像制作csv数据集?

问题描述 投票:0回答:1

我正在制作一个机器学习项目来识别不同用户的轮廓。我有一个包含 1900 张图像的原始图像数据集。我想将它们转换为 csv 数据集,其中标签是用户的姓名。我目前坚持将图像转换为 numpy 数组的部分。代码在这里

from PIL import Image
import numpy as np
import sys
import os
import csv


# default format can be changed as needed
def createFileList(myDir, format='.jpg'):
    fileList = []
    print(myDir)
    for root, dirs, files in os.walk(myDir, topdown=False):
        for name in files:
            if name.endswith(format):
                fullName = os.path.join(root, name)
                fileList.append(fullName)
    return fileList


rahul = []

# load the original image
myFileList = createFileList(r'C:\Users\Mr.X\PycharmProjects\Gait_Project\data\rahul')

for file in myFileList:
    print(file)
    img_file = Image.open(file)
    # img_file.show()

    # get original image parameters...
    width, height = img_file.size
    format = img_file.format
    mode = img_file.mode

    # Make image Greyscale
    img_grey = img_file.convert('L')
    img_res = img_grey.resize((480, 272))
    # img_grey.save('result.png')
    # img_grey.show()

    # Save Greyscale values
    value = np.asarray(img_res.getdata(), dtype=np.int).reshape((img_res.size[1], img_res.size[0]))
    value = value.flatten()
    print(value)
    npvalue = np.array(value)
    rahul.append(npvalue)

    #with open("rahul.csv", 'a') as f:
    #    writer = csv.writer(f)
    #    writer.writerow(value)

final = np.array(rahul)
np.save("rahul.npy", final)

我的目标是制作一个包含 1900 个图像和 4 个标签的数据集,目前在制作 numpy 数组时,图像的每个像素都输入到单独的列中。如果 1900 行和 200k 列需要变成 1900 行和 2 列。任何建议或帮助表示赞赏

python numpy csv machine-learning dataset
1个回答
0
投票

您可以轻松打开图像并使用 OpenCV 将其转换为 NumPy。

import cv2

img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # returns np array


© www.soinside.com 2019 - 2024. All rights reserved.