在python中将图像转换为csv文件

2024-04-20 12:32:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经将我的图像转换成csv文件,它就像一个矩阵,但我希望它是一行。 如何将数据集中的所有图像转换为csv文件(每个图像都转换为一行)。

这是我用过的代码:

from PIL import Image
import numpy as np
import os, os.path, time

format='.jpg'
myDir = "Lotus1"
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

fileList = createFileList(myDir)
fileFormat='.jpg'
for fileFormat in fileList:
 format = '.jpg'
 # get original image parameters...
 width, height = fileList.size
 format = fileList.format
 mode = fileList.mode
 # Make image Greyscale
 img_grey = fileList.convert('L')
 # Save Greyscale values
 value = np.asarray(fileList.getdata(),dtype=np.float64).reshape((fileList.size[1],fileList.size[0]))
 np.savetxt("img_pixels.csv", value, delimiter=',')

输入: http://uupload.ir/files/pto0_lotus1_1.jpg

输出:http://uupload.ir/files/huwh_output.png


Tags: 文件csvnamein图像importformatfor
3条回答

如何将图像转换为2D numpy数组,然后将其作为txt文件写入,扩展名为.csv,分隔符为

也许你可以使用如下代码:

np.savetxt('np.csv', image, delimiter=',')
import numpy as np
import cv2
import os

IMG_DIR = '/home/kushal/Documents/opencv_tutorials/image_reading/dataset'

for img in os.listdir(IMG_DIR):
        img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_GRAYSCALE)

        img_array = (img_array.flatten())

        img_array  = img_array.reshape(-1, 1).T

        print(img_array)

        with open('output.csv', 'ab') as f:

            np.savetxt(f, img_array, delimiter=",")

从你的问题来看,我认为你想知道numpy.flatten()。你想添加

value = value.flatten()

就在您的np.savetxt调用之前。它会将数组展平到只有一个维度,然后应该作为一行打印出来。

你的问题的其余部分是不清楚的一点,它意味着你有一个目录充满了jpeg图像,你想要一种方法来阅读所有这些图像。因此,首先,获取一个文件列表:

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

for fileName in fileList:包围代码

编辑以添加完整示例 注意,我使用了csv writer并将float64更改为int(这应该是正常的,因为像素数据是0-255

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

#Useful function
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

# load the original image
myFileList = createFileList('path/to/directory/')

for file in fileList:
    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_grey.save('result.png')
    #img_grey.show()

    # Save Greyscale values
    value = np.asarray(img_grey.getdata(), dtype=np.int).reshape((img_grey.size[1], img_grey.size[0]))
    value = value.flatten()
    print(value)
    with open("img_pixels.csv", 'a') as f:
        writer = csv.writer(f)
        writer.writerow(value)

相关问题 更多 >