处理python中除0错误和nan问题



我正在尝试使用此代码计算图像的平均对比度:

from google.colab import drive
drive.mount('/content/drive')
pip install mahotas
import numpy as np
import cv2
import os
import mahotas
from skimage.io import imread
from skimage.transform import resize
import pandas as pd
from numpy import *

data_path = "/content/drive/My 
Drive/ADIP/seperate_ricepests5/seperate_ricepests5/"
x_image = []
y_label = []
image_dataset = pd.DataFrame()
labels = os.listdir(data_path)
for dirname in labels:
filepath = os.path.join(data_path, dirname)
print("Extracting ",dirname," ... ")
for file in os.listdir(filepath):
filename = os.path.join(filepath, file)       
image = cv2.imread(filename)
image_resized = cv2.resize(image, (300,300))
image_gray = cv2.cvtColor(image_resized, cv2.COLOR_BGR2GRAY)     
df = pd.DataFrame()
lab = cv2.cvtColor(image_resized,cv2.COLOR_BGR2LAB)
L,A,B=cv2.split(lab)
# compute minimum and maximum in 5x5 region using erode and 
dilate
kernel = np.ones((5,5),np.uint8)
min = cv2.erode(L,kernel,iterations = 1)
max = cv2.dilate(L,kernel,iterations = 1)
# convert min and max to floats
min = min.astype(np.float64) 
max = max.astype(np.float64) 
# compute local contrast
#contrast = (max-min)/(max+min)
try:
contrast = (max-min)/(max+min)
except ZeroDivisionError:
contrast = 0
#print(contrast)

average_contrast = 100*np.mean(contrast)
print(average_contrast)

#average_contrast = 0 if isnan(contrast.all) else 
100*np.mean(contrast)
df['Average_Contrast'] = str(average_contrast)
image_dataset = image_dataset.append(df)

问题-1:当它在第(1)行上计算局部对比度时,它被0除并给出错误。问题2:我不想看到nan,我想看到0而不是nan。

我试了很多次,但都没有找到解决办法。

错误(使用传递给此代码的图像集)

12.399144455618014
8.153193046496428
21.500097694214016
6.484668625777974
4.184483018281615
7.769430843626425
6.542391950067563
8.547638297275716
9.426613716832737
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:147: RuntimeWarning: invalid 
value encountered in true_divide
nan
6.25553159262818
10.847396421660804
nan

如果您的问题是发生除零的事实,您可以尝试更改此:

contrast = (max-min)/(max+min)

:

epsilon = 2.22e-308
contrast = (max - min)/(max + min + epsilon)

您可以尝试在特定错误的情况下引发异常。

a = 5
b = 0
try:
print(a/b)
except ZeroDivisionError:
print("You can't divide by zero!")

我想对你来说应该是这样的

max = 10
min = -10
try:
contrast = (max - min) / (max + min)
print(contrast)
except ZeroDivisionError:
contrast = 0
print('You tried to divide by zero!')

首先,不要使用内置的maxmin作为变量名。

假设变量名为ab,则可以使用np.where:

np.random.seed(0)
a = np.random.rand(5,5).astype(np.float64)
b = np.random.rand(5,5).astype(np.float64)
#Set zeros to force division by 0
a[1][1] = 0
b[1][1] = 0
>>> np.where(b+a==0, 0, b-a/b+a)
array([[  0.33110759,  -4.13045606,   0.9093639 ,   0.02259059, -0.18337047],
[ -1.53098067,   0.64663339,  -0.6070747 ,  -0.16319746, -20.0046655],
[  0.127496  ,   0.27691841,   0.26422437,   0.88857807,  0.64867046],
[  0.20428008,   0.41098738,   0.33675532, -12.08234268,  0.23195646],
[  0.19002108,  -2.78905587,  -2.98899878,  -1.37854793,  0.15679707] 
])

最新更新