数学域错误(Python):ValueError

4
我正在测试数学模块和 PIL 模块,并尝试在图像上应用盒子计数算法。当我运行下面的代码时,会出现以下错误:
Traceback (most recent call last):
  File "C:\Users\Joao\Desktop\Image Size.py", line 48, in <module>
    gy.append(math.log(boxCount))
ValueError: math domain error

代码:

import Tkinter as tk
from Tkinter import *
from PIL import Image, ImageTk
import os, glob, tkFileDialog
import math


im = Image.open("img1.bmp")
width, height = im.size
print width
print height

imgx = width
imgy = height

pixels = im.load()
theColor = (255, 255, 255)


# fractal dimension calculation using box-counting method
b = 2 # initial box size in pixels
f = 2 # box scaling factor
n = 3 # number of graph points for simple linear regression
gx = [] # x coordinates of graph points
gy = [] # y coordinates of graph points
for ib in range(n):
    bs = b * f ** ib # box size in pixels
    bnx = int(imgx / bs) # of boxes in x direction of image
    bny = int(imgy / bs) # of boxes in y direction of image
    boxCount = 0
    for by in range(bny):
        for bx in range(bnx):
        # if there are any pixels in the box then increase box count
            foundPixel = False
            for ky in range(bs):
                for kx in range(bs):
                    if pixels[bs * bx + kx, bs * by + ky] == theColor:
                        foundPixel = True
                        boxCount += 1
                        break
                if foundPixel:
                    break
    gx.append(math.log(1.0 / bs))
    gy.append(math.log(boxCount))

我发现如果将boxcount的值更改为1(而不是零),就不会产生任何错误,但我需要boxcount的值为0。有人能提供一个解决方案吗?

错误显示很可能是你在对0进行登录。 为什么你的boxCount是0?你有BMP文件的链接吗? - smushi
@smushi 为了让算法正常工作,初始箱子计数必须为零。是的,我有:https://www.dropbox.com/s/lahmh8v3pi31eqc/img1.bmp?dl=0 - svacx
1个回答

5
由于负数或零的对数未定义。因此,请替换为:
gy.append(math.log(boxCount))

有了这个:

gy.append(math.log(boxCount if boxCount>0 else 1))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接