【发布时间】:2018-11-27 07:42:56
【问题描述】:
我编写了一个程序来根据灰度图像构建阈值并找到其较低对象的中心。这进一步用于将几何图形(线)绘制到对象中。 cv2.PCACompute() 函数用于查找对象的中心。完成后,我可以绘制线条以匹配对象的大致形状并进行进一步分析。
所以:
对象的极值是我需要找到的重要东西,而不是中心。但是要计算它们,我需要从中心画一条线。问题在于,我需要告诉程序对象的size。现在我正在尝试通过检测对象的极值而不是中心来自动执行此操作。我想知道你是否可以帮助我。
输入图像:
首先建立一个阈值并从中移除上面的对象:
import cv2
import numpy as np
#required to draw the length of the lins, originating from the core of object
scale = 20 #factor by which original image was scaled up
shard_size = 12*scale #length of object
#import image
img = cv2.imread('img.png', 0)
#build threshold
_, thresh = cv2.threshold(img,
235,
255,
cv2.THRESH_BINARY)
#remove upper object from image
z = 0
for x in thresh[::-1]:
v = 0
for el in x:
if el > 0:
break
v += 1
z += 1
if el > 0:
thresh[:int(-z-shard_size-2*scale)] = 0
break
如您所见,对象在顶部被切割。这是一种笨拙的方法。在下一步中,cv2.PCACompute() 用于找到对象的中心并确定其极值的方向。通过提供shard_size,可以在对象极值的方向上绘制一条线。
#compute geometry of object (center + line extrema)
mat = np.argwhere(thresh == 255)
mat[:, [0, 1]] = mat[:, [1, 0]]
mat = np.array(mat).astype(np.float32)
m, e = cv2.PCACompute(mat, mean = np.array([]))
#determine coordinates of object (center + line extrema)
center = tuple(m[0])
endpoint1 = tuple(m[0] - e[0] * shard_size/2)
endpoint2 = tuple(m[0] + e[0] * shard_size/2)
#draw line into object
red_color = (0, 0, 255)
coord1 = endpoint1
coord2 = endpoint2
cv2.circle(img, center, 1, red_color)
cv2.line(img, coord1, coord2, red_color)
#save output img
cv2.imwrite('output_img.png', img)
如何找到对象的极值而不是中心,这样我就不需要再给程序shard_size输入了?
【问题讨论】:
-
是否有类似最接近的边界框(不是轴对齐)?
-
对不起,什么意思?
-
在阈值操作之后,您会得到一个二值图像 - 通常光像素包含一个 ROI“感兴趣区域”,可以对其几何属性进行某些操作:面积、最小封闭圆、轴对齐边界框,最小边界框等。最后一个可能是拉出长轴长度的最佳选择。或者,可能有一个“最大直径”,它或多或少地说明了这个形状。
标签: python opencv object-detection