简体   繁体   English

类型错误:需要一个整数

[英]TypeError: an integer is required

Beginner to Python, I've been trying to alter the pixel values of an image as follows. Python 初学者,我一直在尝试按如下方式更改图像的像素值。 I've been getting an error that says 'TypeError: an integer is required'on the last but one line How do I sort this out?我收到一条错误消息,显示“TypeError: an integer is required”在最后一行但如何解决? This is my code:这是我的代码:

from PIL import Image
img = Image.open(r'...')
pix = img.load()
def quantf(pval):
    if pval>=0 and pval<0.25:
        pval=0
    elif pval>=0.25 and pval<0.5:
       pval=0.25
    elif pval>=0.5 and pval<0.75:
        pval=0.5
    elif pval>=0.75 and pval<1:
        pval=0.75
    elif pval==1:
        pval=1   
for i in range (0,31):
    for j in range (0,31):
        pix[i,j]=quantf(pix[i,j])
img.show()

According to:根据:

http://pillow.readthedocs.io/en/3.4.x/reference/PixelAccess.html#example http://pillow.readthedocs.io/en/3.4.x/reference/PixelAccess.html#example

After performing an image load each pixel is a tuple when using a multi-band image, otherwise it's an individual value:执行图像加载后,当使用多波段图像时,每个像素都是一个元组,否则它是一个单独的值:

from PIL import Image
im = Image.open('hopper.jpg')
px = im.load()
print (px[4,4])

prints:印刷:

(23, 24, 68)

or或者

0.23

You'll need to adjust your quantf(pval) function in order to account for this as well as ensuring that quantf(pval) actually returns a value.您需要调整quantf(pval)函数以解决此问题并确保quantf(pval)实际返回一个值。

For example:例如:

def quantf(pval):
    if pval[0]>=0 and pval[0]<64:
        pval=(0, pval[1], pval[2])
    elif pval[0]>=64 and pval[0]<128:
        pval=(64, pval[1], pval[2])
    elif pval[0]>=128 and pval[0]<192:
        pval=(128, pval[1], pval[2])
    elif pval[0]>=192 and pval[0]<256:
        pval=(192, pval[1], pval[2])
    return pval

or或者

def quantf(pval):
    if pval>=0 and pval<0.25:
        pval=0
    elif pval>=0.25 and pval<0.5:
        pval=0.25
    elif pval>=0.5 and pval<0.75:
        pval=0.5
    elif pval>=0.75 and pval<1:
        pval=0.75
    elif pval==1:
        pval=1
    return pval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM