枕头图像TypeError:需要一个整数(得到类型元组)

时间:2016-09-23 04:09:42

标签: python image python-3.x python-imaging-library pillow

我有点迷失为什么会发生任何帮助将不胜感激。所以我试图获取图像的中值并从中创建一个新图像,但是当尝试使newpix采用我的红绿蓝像素值时,错误:

TypeError:需要一个整数(得到类型元组)

发生

from PIL import Image, ImageChops,ImageDraw,ImageFilter
import math
import glob
import os.path
from os import  listdir;
import numpy


image_list = []

redPixels = []
greenPixels = []
bluePixels = []

for filename in glob.glob(r"C:\Users\Elias\Desktop\Proj1\images\*.png"):
    im = Image.open(filename)
    image_list.append(im)
im = Image.open(open(r"C:\Users\Elias\Desktop\Proj1\images\1.png",'rb'))
width, height = im.size
print(height)
print (width)

result = Image.new('RGB', (width,height))
newpix = result.load()
for x in range (width):
    for y in range (height):
        for z in (image_list):
            red  = z.getpixel((x,y))
            blue = z.getpixel((x,y))
            green = z.getpixel((x,y))

            redPixels.append(red)
            greenPixels.append(green)
            bluePixels.append(blue)
        red = sorted(redPixels)
        blue = sorted(bluePixels)
        green = sorted(greenPixels)

        mid = int( (len(image_list)+1)/2)-1

        newRed = redPixels[mid]
        newBlue = bluePixels[mid]
        newGreen = greenPixels[mid]
        newpix[x,y] = (newRed,newGreen,newBlue)

result.save("Stacked.png")

1 个答案:

答案 0 :(得分:2)

问题在于

        red  = z.getpixel((x,y))
        blue = z.getpixel((x,y))
        green = z.getpixel((x,y))

        redPixels.append(red)
        greenPixels.append(green)
        bluePixels.append(blue)

red = z.getpixel((x,y))将获得x,y位置的所有R,G,B数据,因此它将是元组(255,255,255)。因此,如下所示对代码进行更改使其起作用:

from PIL import Image, ImageChops,ImageDraw,ImageFilter
import math
import glob
import os.path
from os import  listdir;
import numpy


image_list = []

redPixels = []
greenPixels = []
bluePixels = []

for filename in glob.glob(r"C:\Users\Elias\Desktop\Proj1\images\*.png"):
    im = Image.open(filename)
    image_list.append(im)
im = Image.open(open(r"C:\Users\Elias\Desktop\Proj1\images\1.png",'rb'))
width, height = im.size
print(height)
print (width)

result = Image.new('RGB', (width,height))
newpix = result.load()
for x in range (width):
    for y in range (height):
        for z in (image_list):
            rgb  = z.getpixel((x,y))
            redPixels.append(rgb[0])
            greenPixels.append(rgb[1])
            bluePixels.append(rgb[2])
        red = sorted(redPixels)
        blue = sorted(bluePixels)
        green = sorted(greenPixels)

        mid = int( (len(image_list)+1)/2)-1
        newRed = redPixels[mid]
        newBlue = bluePixels[mid]
        newGreen = greenPixels[mid]

        newpix[x,y] = (newRed,newGreen,newBlue)

result.save("Stacked.png")