ValueError: ошибка математического домена (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. Кто-нибудь может предложить решение?


person santoznma    schedule 27.10.2014    source источник
comment
Ошибка показывает, что, вероятно, означает, что вы ведете журнал 0. Почему ваш boxCount 0? У вас есть ссылка на файл BMP?   -  person smushi    schedule 27.10.2014
comment
@smushi Чтобы алгоритм работал, начальное количество ящиков должно быть равно нулю. Да, знаю: dropbox.com/s/lahmh8v3pi31eqc/img1.bmp? дл=0   -  person santoznma    schedule 27.10.2014


Ответы (1)


Поскольку журнал отрицательного или нулевого значения не определен. Поэтому замените:

gy.append(math.log(boxCount))

с этим :

gy.append(math.log(boxCount if boxCount>0 else 1))
person Irshad Bhat    schedule 27.10.2014