这是我previous question的继续。我现在有这样的图像

python - OpenCV-估计Python中的框尺寸-LMLPHP

在此检测到拐角。现在,我正在尝试估计较大的盒子的尺寸,而已知较小的黑色盒子的尺寸。

谁能指导我估计盒子尺寸的最佳方法是什么?我可以用简单的欧几里得距离来做到这一点,但我不知道这是否是正确的方法。或者即使这是正确的方法,那么如何从元组(坐标)列表中找到像A-B或A-D或G-H之类的距离,却找不到像A-C或A-F那样的距离?

必须保留顺序才能获得正确的尺寸。另外我在这里有两个盒子,所以当我创建角坐标列表时,它应该包含A-J的所有坐标,我不知道哪个坐标属于哪个盒子。因此,如何为两个不同的框保留该框,因为我想为更相似的图像运行此代码。

注意:此图像中的角不是单个点,而是一组点,因此我将角的集合聚类并求平均值,以获取每个角的单个(x,y)坐标。

我已经尽力解释了我的问题。会有一些答案将非常高兴:)谢谢。

最佳答案

为了



部分

这是一个快速的代码,对于有很多拐角的图像来说效率不高,但是对于您的情况来说,可以。这个想法是从您在另一个问题中得到的扩大的边缘图像开始的(只有大盒子,但是对于有小盒子的图像,想法也是一样的)
python - OpenCV-估计Python中的框尺寸-LMLPHP

然后针对每个可能的拐角组合,查看它们之间的假想线上的几个点,然后检查这些点是否实际上落在图像的真实线上。

import cv2
import numpy as np

#getting intermediate points on the line between point1 and point2
#for example, calling this function with (p1,p2,3) will return the point
#on the line between p1 and p2, at 1/3 distance from p2
def get_intermediate_point(p1,p2,ratio):
    return [p1[0]+(p2[0]-p1[0])/ratio,p1[1]+(p2[1]-p1[1])/ratio]

#open dilated edge images
img=cv2.imread(dilated_edges,0)

#corners you got from your segmentation and other question
corners=[[29,94],[102,21],[184,52],[183,547],[101,576],[27,509]]
nb_corners=len(corners)

#intermediate points between corners you are going to test
ratios=[2,4,6,8] #in this example, the middle point, the quarter point, etc
nb_ratios=len(ratios)

#list which will contain all connected corners
connected_corners=[]

#double loop for going through all possible corners
for i in range(nb_corners-1):
    for j in range(i+1,nb_corners):
        cpt=0
        c1=corners[i]; c2=corners[j]

        #testing every intermediate points between the selected corners
        for ratio in ratios:
            p=get_intermediate_point(c1,c2,ratio)

            #checking if these points fall on a white pixel in the image
            if img[p[0],p[1]]==255:
                cpt+=1

        #if enough of the intermediate points fall on a white pixel
        if cpt>=int(nb_ratios*0.75):
            #then we assume that the 2 corners are indeed connected by a line
            connected_corners.append([i,j])

print(connected_corners)

09-30 16:01
查看更多