简体   繁体   中英

TypeError: an integer is required

Beginner to Python, I've been trying to alter the pixel values of an image as follows. 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? 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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