在图片上选边缘点以用来生成TSP art并输出tsplib数据集python代码
时间: 2023-06-17 07:08:34 浏览: 179
以下是一个简单的 Python 代码示例,用于从图像中选择边缘点并生成 TSP art 和 tsplib 数据集:
```python
import numpy as np
import cv2
# Load image
img = cv2.imread("input.jpg")
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect edges
edges = cv2.Canny(gray, 100, 200)
# Display image with edges
cv2.imshow("Image with Edges", edges)
# Select edge points using a mouse click
points = []
def select_point(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
points.append((x, y))
cv2.namedWindow("Select Points")
cv2.setMouseCallback("Select Points", select_point)
while True:
cv2.imshow("Select Points", img)
key = cv2.waitKey(1)
if key == ord("q"):
break
# Generate TSP art and tsplib dataset
n = len(points)
distances = np.zeros((n, n))
for i in range(n):
for j in range(n):
if i != j:
distances[i][j] = np.sqrt((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2)
# Write tsplib dataset
with open("output.tsp", "w") as f:
f.write("NAME: output\n")
f.write("TYPE: TSP\n")
f.write("DIMENSION: {}\n".format(n))
f.write("EDGE_WEIGHT_TYPE: EUC_2D\n")
f.write("NODE_COORD_SECTION\n")
for i in range(n):
f.write("{} {} {}\n".format(i+1, points[i][0], points[i][1]))
f.write("EOF\n")
# Display TSP art
tsp_art = np.zeros_like(gray)
path = list(range(n)) + [0]
for i in range(n):
cv2.line(tsp_art, points[path[i]], points[path[i+1]], (255, 255, 255), thickness=1)
cv2.imshow("TSP Art", tsp_art)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该代码使用 OpenCV 库加载图像、将其转换为灰度图像、检测边缘,并允许用户使用鼠标单击选择边缘点。通过这些点,代码将生成 TSP art 和 tsplib 数据集。最后,使用 OpenCV 显示生成的 TSP art。
阅读全文