ZeroDivisionError (Python)

百般思念 提交于 2019-11-30 16:08:26

Error is self-evident. You cannot divide a number by zero. If M["m00"] is zero, then you need to handle it appropriately. Check for 0 values in M["m00"].

if M["m00"] != 0:
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
else:
    # set values as what you need in the situation
    cX, cY = 0, 0

Probably you have bad contours

Note Since the contour moments are computed using Green formula, you may get seemingly odd results for contours with self-intersections, e.g. a zero area (m00) for butterfly-shaped contours.

Calculate the the center of mass, e.g.:

cx = 0
cy = 0
for p in contour:
    cx += p[0][0]
    cy += p[0][1]
cx = int(cx/len(contour))
cy = int(cy/len(contour))

or look into boundingRect() (3.4.3).

Related: Finding the center of a contour using opencv and visual c++

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!