我是Python的新手。 我想从多个图像中提取RGB值。我想使用每个图像的RGB值作为K倍交叉验证的输入。你知道吗
我只能得到一个图像的RGB值。因此,我尝试使用以下代码从多个图像中获取:
from __future__ import with_statement
from PIL import Image
import glob
#Path to file
for img in glob.glob({Path}+"*.jpg"):
im = Image.open(img)
#Load the pixel info
pix = im.load()
#Get a tuple of the x and y dimensions of the image
width, height = im.size
#Open a file to write the pixel data
with open('output_file.csv', 'w+') as f:
f.write('R,G,B\n')
#Read the details of each pixel and write them to the file
for x in range(width):
for y in range(height):
r = pix[x,y][0]
g = pix[x,x][1]
b = pix[x,x][2]
f.write('{0},{1},{2}\n'.format(r,g,b))
我希望在CSV文件中得到如下输入:
img_name,R,G,B
1.jpg,50,50,50
2.jpg,60,60,70
但实际输出是包含40000多行的CSV文件。你知道吗
是否可以从多个图像中自动获取RGB值?你知道吗
您的代码当前正在CSV文件中将每个像素的值作为一个单独的行写入,因此您可能有大量的行。你知道吗
要处理多个文件,需要稍微重新排列代码,并在循环中缩进文件。利用Python的CSV库来编写CSV文件也是一个好主意,以防您的任何文件名包含逗号。如果发生这种情况,它将正确地用引号将字段括起来。你知道吗
注意:获取
r
g
b
值也有问题,在两种情况下有[x,x]
。你知道吗正如@GiacomoCatenazzi所指出的,您的循环也可以被删除:
相关问题 更多 >
编程相关推荐