【问题标题】:Thinness ratio calculation - wrong results薄度比计算 - 错误的结果
【发布时间】:2020-01-20 19:14:25
【问题描述】:

我在计算薄度比时遇到问题。它给了我 0.9 而不是 1 的值。

薄度以a给出

(4 * pi * area) / (perimeter * perimeter)

对于圆,上述等式的结果应该是 1.0。

import cv2
import math
image = cv2.imread("circle.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cnt = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]

for c in cnt:
            # compute the area of the contour along with the bounding box
            # to compute the aspect ratio
            area = cv2.contourArea(c)
            perimeter = cv2.arcLength(c,True)
ti= (4*area*math.pi)/(perimeter**2)
print(ti)

【问题讨论】:

  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。您发布的代码包括图形输入、两个函数调用和一个计算。差异发生在哪里?
  • 你试过cv2.CHAIN_APPROX_NONE吗?
  • cv2.CHAIN_APPROX_NONE 函数给了我同样的结果

标签: python algorithm opencv optimization geometry


【解决方案1】:

我认为这是由于轮廓查找代码返回了一个精确的轮廓,这可能是由于混叠错误,实际上比它应该的要长。如果我平滑生成的轮廓,我会得到 ~1 的“正确”值。

import cv2
import numpy as np
from scipy.interpolate import splprep, splev

image = cv2.imread("circle.png", 0)
_, thresh = cv2.threshold(image, 127, 255, 0)

# remove extra dimensions here to simplify later code
[contour], hierarchy = cv2.findContours(thresh, 1, 2)
contour = contour[:,0,:]

# smooth contour
tck, u = splprep(contour.T, u=None, s=30, per=1)
u_new = np.linspace(u.min(), u.max(), 50)
new_cont = np.column_stack(splev(u_new, tck, der=0))

# change types to stop cv2 complaining
new_cont = new_cont.astype(np.float32)

# calculate as before
area = cv2.contourArea(new_cont)
circum = cv2.arcLength(new_cont, True)

(4 * pi * area) / (circum**2)

给我 0.9986,这对我来说没问题。请注意,如果您运行的是 OpenCV 版本 3,则需要将 findContours 行更改为 returns a triple instead of a pair of values。

我从here 借用了bspline 平滑代码,而这似乎又从here 借来了。您可以使用各种平滑因子(尝试将 s 降低到 1),以及在哪里对其进行采样(将最后一个参数更改为 linspace)。

【讨论】:

  • 谢谢山姆!我也知道混叠错误,但我不认为这是原因。第 9 行应更改为_, [contour], hierarchy = cv2.findContours(thresh, 1, 2),如此处link 所述。我今天需要用我的其他案例测试代码,如果它有效,我会将您的答案标记为已接受。
  • 呵呵,你运行的肯定是老版本了,明显改了a year ago。如果可以的话,可能值得更新,大概还会有很多其他错误修复
  • 你说得对,再次感谢!我检查并使用了anaconda包附带的那个。那时它已经很老了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
相关资源
最近更新 更多