图像分析,物体形状,中心和极值

时间:2018-11-27 07:42:57

标签: python opencv object-detection

我编写了一个程序,用于从灰度图像建立阈值,并找到其对象的中心。这进一步用于将几何图形(线)绘制到对象中。 public void BaackgroundImagesHP(){ WebElement body = Driver.Gprops.GetWebDriver().findElement(By.id("ImagePlaceHolder")); System.out.println("body is "+body); String actual = body.getCssValue("background-image"); System.out.println("Actual is "+actual); } 函数用于查找对象的中心。完成此操作后,我可以画线以匹配对象的近似形状并进行进一步分析。

所以:

对象的极值是我需要找到的重要内容,而不是中心。但是要计算它们,我需要画一条从中心开始的线。问题在于,我需要告诉程序对象的cv2.PCACompute()。现在,我正在尝试通过检测对象的极值而不是中心来使其自动化。我想知道您是否可以帮助我。

输入图像:

enter image description here

首先建立一个阈值,并从中删除上层对象

size

enter image description here

如您所见,对象在顶部被剪切。这是一种笨拙的方法。在下一步中,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

enter image description here

如何找到对象的极值而不是中心,所以我不再需要为程序提供#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) 输入了吗?

1 个答案:

答案 0 :(得分:1)

在这里,我使用cv2.minAreaRect()函数找到了对象的长度,并计算了沿质心的端点。

minAreaRect函数为我们提供了包围对象的矩形的中心,轴和角度。我使用角度信息旋转水平矢量并生成线的端点

#Finding the contours in the image
im2, contours, hierarchy = cv2.findContours(img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

#finding the minimum area rectangle that covers the blob
rect = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)

#Forming the line vector
v = np.matrix([[0], [1]])

#forming the rotation matrix to rotate the line vector
ang = rect[2]* np.pi / 180 #conversion to radians
rot = np.matrix([[np.cos(ang), -np.sin(ang)],[np.sin(ang), np.cos(ang)]])

#Rotating the horizontal vector
rv = rot*v

#half length of the line
lineSize = max(rect[1])*0.5

#extreme points of the line
p1 = tuple(np.array(rect[0] - lineSize*rv.T)[0].astype(int))
p2 = tuple(np.array(rect[0] + lineSize*rv.T)[0].astype(int))

cv2.line(img, p1, p2, (0,255,0), 2)

Output