使用PIL实现对数映射时遇TypeError: 'int' object is not subscriptable错误求助
Hey there, let's break down why you're running into this error and get your logarithmic mapping code working properly.
The Root Cause
That TypeError pops up because when you call photo.getdata(), each entry in the data list is a single integer—not an RGB tuple. This is almost certainly because your input image TurtleLuminance.jpg is a grayscale (single-channel) image. When you tried to access data[x][0], data[x][1], data[x][2], you were trying to index into an integer value, which Python doesn't allow.
Fix for Grayscale Images
If you intended to work with the grayscale image directly, here's the corrected code:
from PIL import Image import math # Open the image and explicitly convert to grayscale to ensure consistency photo = Image.open('TurtleLuminance.jpg').convert('L') data = photo.getdata() # Calculate the scaling constant for log mapping c = 255 / math.log(1 + 255) # Apply the logarithmic transform to each pixel logarithmic = [int(c * math.log(1 + pixel)) for pixel in data] # Create and save the transformed image gray_image = Image.new('L', photo.size) gray_image.putdata(logarithmic) gray_image.save('TurtleLogarithmic.jpg')
Key changes here:
- Added
.convert('L')to guarantee we're working with a single-channel grayscale image, so every element indatais an integer we can use directly. - Simplified the list comprehension to iterate over
datadirectly (no need forrange(len(data))and indexing) which makes the code cleaner and avoids the subscript error.
If You Meant to Process RGB Luminance
If your original image is RGB and you wanted to compute luminance from the three channels before applying the log transform (like your original code tried to do), use this version instead:
from PIL import Image import math # Open the image and convert to RGB to ensure tuple-based pixel data photo = Image.open('TurtleLuminance.jpg').convert('RGB') data = photo.getdata() c = 255 / math.log(1 + 255) logarithmic = [] for r, g, b in data: # Calculate simple average luminance (use weighted values like 0.299*r + 0.587*g + 0.114*b for more accurate human-perceived brightness) luminance = (r + g + b) / 3 log_pixel = int(c * math.log(1 + luminance)) logarithmic.append(log_pixel) gray_image = Image.new('L', photo.size) gray_image.putdata(logarithmic) gray_image.save('TurtleLogarithmic.jpg')
This version:
- Converts the image to RGB explicitly, so each entry in
datais an (r, g, b) tuple we can unpack safely. - Uses a straightforward loop to calculate luminance (you can swap in the weighted formula if you want more accurate results aligned with how humans see brightness) before applying the log mapping.
内容的提问来源于stack exchange,提问作者Rembrandt Sánches Dosal

