繁体   English   中英

ValueError:数学域错误(python)

[英]ValueError: math domain error (python)

我正在测试数学模块和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。有人可以建议解决方案吗?

由于未定义对数为负数或零,因此请替换:

gy.append(math.log(boxCount))

有了这个 :

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

暂无
暂无

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

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