我正在将OpenCV与python一起用于我的图像处理项目之一。在那里,我创建了要插入subdiv2d
对象的点的列表,并使用getTriangleList
方法检索Delaunay三角形。同时,我创建一个python字典并添加点列表(插入subdiv2d的列表)的每个点作为键并分配一些值。最终,我尝试使用三角形顶点(从subdiv2d.getTriangleList()
返回)作为键从我创建的字典中检索值。结果将以KeyError结尾。这是一个示例代码,可以帮助您进一步理解。
points = []
rect = (0, 0, size[0], size[1])
subdiv = cv2.Subdiv2D(rect)
imgDictionary = {}
for t in data: #data that recieved from another method with [num, num, num] format
x = t[0]
y = t[1]
value = t[2]
imgDictionary[(x,y)] = value
points.append((x, y))
subdiv.insert(points)
triangleList = subdiv.getTriangleList()
for t in triangleList:
p1 = (int(t[0]), int(t[1]))
p2 = (int(t[2]), int(t[3]))
p3 = (int(t[4]), int(t[5]))
#to ensure all the points are inside the rectangle
if rect_contains(rect, p1) and rect_contains(rect, p2) and rect_contains(rect, p3):
value = imgDictionary[p1] #here come the KeyError
...
之前我认为会发生这种情况,因为有一些三角形的点不在`subdiv的范围内。但是由于我们使用rect_ contains方法来避免超出细分范围的顶点。
请帮助我找到合适的解决方案,以使用具有元组数据对象的键从字典中检索值。