我在用Python写椭圆检测的时候,运行程代码之后报错如下:
Traceback (most recent call last):
File "<ipython-input-49-10e78ddea753>", line 1, in <module>
runfile('E:/pythonfile/ellipse_detection.py', wdir='E:/pythonfile')
File "E:Anacondalibsite-packagesspyderutilssitesitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "E:Anacondalibsite-packagesspyderutilssitesitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "E:/pythonfile/ellipse_detection.py", line 70, in <module>
ellipse_detection(img_canny,5,100,10)
ValueError: math domain error
代码:
from numba import jit
import cv2
import numpy as np
import math
def dis(x1,y1,x2,y2):
dis=math.sqrt((x1-x2)**2+(y1-y2)**2)
return dis
class ellipse:
def __init__(self,a,b,pos,alpha):
self.a=a
self.b=b
self.pos=pos
self.alpha=alpha
img=cv2.imread('E:\Image\text2.jpg',0)
img_canny=cv2.Canny(img,200,300)
@jit
def ellipse_detection(img,mina,maxa,min_v):
#ellipses=[]
px,py=np.where(img)
acc=[0]*max(img.shape)
for i in range(len(px)):
for j in range(len(px)-1,i,-1):
x1=px[i]
y1=py[i]
x2=px[j]
y2=py[j]
acc=[0]*max(img.shape)
d12=dis(x1,y1,x2,y2)
a=d12/2
if a>mina and a<maxa:
x0=(x1+x2)/2
y0=(y1+y2)/2
alpha=math.atan2(x2-x1,y2-y1)
for m in range(len(px)):
if m==i or m==j:
continue
x3=px[m]
y3=py[m]
d03=dis(x0,y0,x3,y3)
if d03>=a:
continue
d23=dis(x2,y2,x3,y3)
cos_a=(d03**2+a**2-d23**2)/(2*d03*a)
xx=(cos_a**2)*(d03**2)
yy=(1-cos_a**2)*(d03**2)
b=round(math.sqrt(((a**2)*yy)/(a**2-xx)))
acc[b]+=1
votes=max(acc)
if votes>min_v:
b=acc.index(votes)
ep=ellipse(a,b,[x0,y0],alpha)
#ellipses.append(ep)
epr=int(round(ep.pos[0]))
epc=int(round(ep.pos[1]))
if(img_canny[epr,epc]<255):
img_canny[epr,epc]+=1
ellipse_detection(img_canny,5,100,10)
cv2.namedWindow("001",cv2.WINDOW_NORMAL)
cv2.imshow('001',img_canny)
cv2.waitKey(0)
我感觉是下面这一行出了问题,可能开平方时候有负数
b=round(math.sqrt(((a**2)*yy)/(a**2-xx)))
但是我加了限制条件的,如果有可能令a**2-xx
为负数的话,会直接下一个循环,也就是用了continue
,但是还是报错,如果我把下一面一段代码里面的continue
改成 break
,程序就不报错了,但是事实上,直接跳出循环不是我想要的,按说continue
是可以的啊,希望各位dalao帮帮我!
if m==i or m==j:
continue
x3=px[m]
y3=py[m]
d03=dis(x0,y0,x3,y3)
if d03>=a:
continue