如何从多个图像Python中提取单个RGB通道

时间:2019-05-09 04:19:31

标签: python csv rgb cross-validation converters

我是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

但是实际输出是CSV文件,其中包含40000+行。

是否可以从多个图像中自动执行RGB值?

1 个答案:

答案 0 :(得分:2)

您的代码当前正在将每个像素的值写为CSV文件中的单独一行,因此您可能会有很多行。

要处理多个文件,您需要稍微重新排列代码并缩进循环中写入的文件。最好使用Python的CSV库编写CSV文件,以防万一您的文件名包含逗号。如果发生这种情况,它将正确地将字段用引号引起来。

from PIL import Image
import glob
import os
import csv

#Open a file to write the pixel data
with open('output_file.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(["img_name", "R", "G", "B"])

    #Path to file 
    for filename in glob.glob("*.jpg"):
        im = Image.open(filename) 
        img_name = os.path.basename(filename)

        #Load the pixel info
        pix = im.load()

        #Get a tuple of the x and y dimensions of the image
        width, height = im.size

        print(f'{filename}, Width {width}, Height {height}') # show progress

        #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,y][1]
                b = pix[x,y][2]
                csv_output.writerow([img_name, r, g, b])

注意:获取r g b值也有问题,在两种情况下您拥有[x,x]


如@GiacomoCatenazzi所述,您的循环也可以删除:

from itertools import product
from PIL import Image
import glob
import os
import csv

#Open a file to write the pixel data
with open('output_file.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(["img_name", "R", "G", "B"])

    #Path to file 
    for filename in glob.glob("*.jpg"):
        im = Image.open(filename) 
        img_name = os.path.basename(filename)

        #Load the pixel info
        pix = im.load()

        #Get a tuple of the x and y dimensions of the image
        width, height = im.size

        print(f'{filename}, Width {width}, Height {height}') # show 

        #Read the details of each pixel and write them to the file
        csv_output.writerows([img_name, *pix[x,y]] for x, y in product(range(width), range(height)))