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

2024-04-18 23:00:30 发布

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

我是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值?你知道吗


Tags: thetoin图像importimgforrgb
1条回答
网友
1楼 · 发布于 2024-04-18 23:00:30

您的代码当前正在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])

注意:获取rgb值也有问题,在两种情况下有[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)))

相关问题 更多 >