我有一个csv文件,其中每一行都包含图像的像素值。因此,一行的每一列都包含像素值,最后一行除外,后者包含图像的“标签”,例如“外套”,“礼服”,“凉鞋”等字样(注意:第一行)包含列名,而不是图像)。
我希望将这些行读取为图像,并将它们全部保存(最好按标签排序,例如对于每个标签,依次为“ dress1”,“ dress2”,....,“ sandal1”,“ sandal2”等。)四个标签)。
我尝试了以下方法来进行不带标签分类的保存,但出现错误:
import numpy as np
import csv
import matplotlib.pyplot as plt
i=0
with open('myfile.csv', 'r') as csv_file:
for data in csv.reader(csv_file):
pixels = data[:]
pixels = np.array(pixels, dtype='uint8')
#Reshape the array into 28 x 28 array (As images are 28x28)
pixels = pixels.reshape((28, 28))
i +=1
plt.savefig(str(i))
寻找解决此问题的最有效方法。任何输入将不胜感激。谢谢!
如果最后一列中有名称,则必须在没有last元素的情况下进行转换data[:-1]
。并使用filenamename中的最后一列savefig( data[-1] + str(i) + '.jpg' )
。没有扩展,它可能不知道要写入哪种类型的图像。
您必须分别计算i
每个标签-即 使用字典
i = dict()
i[label] = 0
# later
i[label] += 1
savefig( label + str(i[label]) + '.jpg'
您也可以使用PIL
/'pillow instead of
matplotlib`编写它。
from PIL import Image
image = Image.fromarray(pixels)
image.save(filename)
import numpy as np
import csv
from PIL import Image
counter = dict()
with open('myfile.csv') as csv_file:
csv_reader = csv.reader(csv_file)
# skip headers
next(csv_reader)
for row in csv.reader(csv_reader):
pixels = row[:-1] # without label
pixels = np.array(pixels, dtype='uint8')
pixels = pixels.reshape((28, 28))
image = Image.fromarray(pixels)
label = row[-1]
if label not in counter:
counter[label] = 0
counter[label] += 1
filename = '{}{}.jpg'.format(label, counter[label])
image.save(filename)
print('saved:', filename)
编辑:示例,其中显示了一行数据,以便那些无需下载csv文件即可对其进行测试的人。
import numpy as np
import csv
from PIL import Image
counter = dict()
row = [
255, 0, 0, 0, 0, 0, 255,
0, 255, 255, 255, 255, 255, 0,
0, 255, 0, 255, 0, 255, 0,
0, 255, 255, 255, 255, 255, 0,
0, 255, 0, 0, 0, 255, 0,
0, 255, 255, 255, 255, 255, 0,
255, 0, 0, 0, 0, 0, 255,
'face'
]
pixels = row[:-1]
pixels = np.array(pixels, dtype='uint8')
pixels = pixels.reshape((7, 7))
image = Image.fromarray(pixels)
label = row[-1]
if label not in counter:
counter[label] = 0
counter[label] += 1
filename = '{}{}.png'.format(label, counter[label])
image.save(filename)
print('saved:', filename)
结果face1.png
:
编辑:我检查了您的csv文件,像素不是整数值而是浮点(正,负)值,所以您不能使用uint8
。它必须是float
。
pixels = np.array(pixels, dtype='float')
您可以将图像转换为RGB
或灰度L
以保存它
image = image.convert('RGB')
image = image.convert('L')
但似乎无法转换负值。
使用
plt.imsave(filename, pixels)
我得到了预期的结果
import numpy as np
import csv
from PIL import Image
import matplotlib.pyplot as plt
counter = dict()
with open('gen_image_wgan.csv') as csv_file:
csv_reader = csv.reader(csv_file)
# skip headers
next(csv_reader)
for row in csv_reader:
pixels = row[:-1] # without label
pixels = np.array(pixels, dtype='float')
pixels = pixels.reshape((28, 28))
label = row[-1]
if label not in counter:
counter[label] = 0
counter[label] += 1
filename = '{}{}.png'.format(label, counter[label])
plt.imsave(filename, pixels)
print('saved:', filename)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句