Python 递归补点
任务:
- Python 列表按某一个元素进行排序
- Python 递归插入补点, 列表相加
- Python OpenCV 显示插入点的效果
"""
任务:
1. Python 列表按某一个元素进行排序
2. Python 递归插入补点, 列表相加
3. Python OpenCV 显示插入点的效果
注: 本程序主要作为实例展示, 不推荐生产环境使用
"""
import cv2
import numpy as np
class CRecursionInsert(object):
def __init__(self):
self.canvas = np.zeros((512, 512, 3), np.uint8)
self.srcPtSet = [] # 原始点集
pt = {}
pt["x"]=50
pt["y"]=50
self.srcPtSet.append(pt)
pt = {}
pt["x"]=300
pt["y"]=40
self.srcPtSet.append(pt)
pt = {}
pt["x"]=400
pt["y"]=300
self.srcPtSet.append(pt)
pt = {}
pt["x"]=200
pt["y"]=200
self.srcPtSet.append(pt)
print("原始点集: \n", self.srcPtSet)
self.__show_pt_canvas("src", self.srcPtSet)
def __show_pt_canvas(self, win_name:str, pt_list: list, color: tuple=(0, 255, 0), radius:int=3):
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
_canvas = self.canvas.copy()
# 将列表中的点显示出来
for i in range(len(pt_list)-1):
pt = (pt_list[i]["x"], pt_list[i]["y"])
cv2.circle(_canvas, pt, radius, color, radius, 8, 0)
if (len(pt_list)-1) > 1:
pt2 = (pt_list[i+1]["x"], pt_list[i+1]["y"])
cv2.line(_canvas, pt, pt2, color, 1, 8, 0)
cv2.circle(_canvas, pt2, radius, color, radius, 8, 0)
cv2.imshow(win_name, _canvas)
def __recursion_insert(self, p1, p2, pt_list):
pm = {}
if (p2["x"]-p1["x"]>1):
pm["x"] = int((p2["x"] + p1["x"]) * 0.5 + 0.5)
pm["y"] = int((p2["y"] + p1["y"]) * 0.5 + 0.5)
pt_list.append(pm)
self.__recursion_insert(p1, pm, pt_list)
self.__recursion_insert(pm, p2, pt_list)
def process(self):
def __take_x(elem):
return elem["x"]
# 按照 x 大小排序
self.sortedPtSet = sorted(self.srcPtSet, key=__take_x)
print("原始点集按照 x 从小到大排序后: \n", self.sortedPtSet)
# 初始化插值算法
insert_pt_list = []
for ix in range(len(self.sortedPtSet)-1):
pt1 = self.sortedPtSet[ix]
pt2 = self.sortedPtSet[ix+1]
pt_list = []
self.__recursion_insert(pt1, pt2, pt_list)
insert_pt_list += pt_list
# 对插入后的 list 进行排序
insert_pt_list = sorted(
sorted(insert_pt_list, key=__take_x), key=__take_x)
# for i in range(50):
# print(insert_pt_list[i], " ")
# 显示插值后的点集
self.__show_pt_canvas("result", pt_list=insert_pt_list, color=(0, 255, 255), radius=1)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
obj = CRecursionInsert()
obj.process()
原始点集:
[{'x': 50, 'y': 50}, {'x': 300, 'y': 40}, {'x': 400, 'y': 300}, {'x': 200, 'y': 200}]
原始点集按照 x 从小到大排序后:
[{'x': 50, 'y': 50}, {'x': 200, 'y': 200}, {'x': 300, 'y': 40}, {'x': 400, 'y': 300}]