You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现图像对数变换(log transform)代码运行异常如何解决?

Python图像对数变换代码问题排查

以下是你代码中存在的可直接导致运行失败的问题:

  • 缺失库导入与别名错误:代码中使用的对数方法m.log未定义,且缺少PIL图像处理库的导入声明,需在代码头部添加导入语句,同时将m.log修正为math.log:
import math
from PIL import Image
  • 函数缩进错误:ImgLogarithmic函数定义后的所有逻辑代码未做缩进,不符合Python语法规范,会直接触发语法错误,需将函数名下所有属于函数逻辑的代码统一缩进4个空格。
  • 输出图像尺寸参数颠倒:PIL中Image.size返回顺序为(宽度, 高度),你创建输出图像时将宽高参数颠倒传入,会导致像素遍历时索引越界,应将Image.new('RGB', (img_input.size[1], img_input.size[0]))修改为Image.new('RGB', (img_input.size[0], img_input.size[1]))。
  • HTML转义字符错误:代码中的"是网页复制产生的转义字符,需替换为普通双引号",否则会触发语法错误。

修正后完整可运行代码

import math
from PIL import Image

# 单独计算对数变换值
def logTransform(c, f):
    g = c * math.log(float(1 + f))
    return g

def ImgLogarithmic(img_input, coldepth):
    # 对数变换参数计算
    inputMax = 255
    outputMax = 255
    c = outputMax / math.log(inputMax + 1)

    if coldepth != 24:
        img_input = img_input.convert('RGB')

    # 修正尺寸参数顺序
    img_output = Image.new('RGB', (img_input.size[0], img_input.size[1]))
    pixels = img_output.load()
    for i in range(img_output.size[0]):
        for j in range(img_output.size[1]):
            f = img_input.getpixel((i, j))
            r = round(logTransform(c, f[0]))
            g = round(logTransform(c, f[1]))
            b = round(logTransform(c, f[2]))
            pixels[i,j] = (r, g, b)

    if coldepth == 1:
        img_output = img_output.convert("1")
    elif coldepth == 8:
        img_output = img_output.convert("L")
    else:
        img_output = img_output.convert("RGB")

    return img_output

内容的提问来源于stack exchange,提问作者Anton Surya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:18:01