在图片上选边缘点以用来生成TSP art的python代码
时间: 2023-06-17 19:08:47 浏览: 58
生成TSP art需要先获得图像的边缘点,可以使用Python的OpenCV库来实现。下面是一个简单的代码示例,供参考:
```python
import cv2
import numpy as np
# 加载图像
img = cv2.imread('image.jpg', 0)
# 边缘检测
edges = cv2.Canny(img, 100, 200)
# 膨胀处理,使边缘更加明显
kernel = np.ones((5, 5),np.uint8)
edges = cv2.dilate(edges,kernel,iterations = 1)
# 获取边缘点
edge_points = np.argwhere(edges > 0)
# 输出结果
print(edge_points)
```
这个代码会加载一张名为`image.jpg`的图像,使用Canny算法对其进行边缘检测,并通过膨胀处理增强边缘,最后输出边缘的点集合。你可以根据需要调整Canny算法的参数,以获得更好的效果。
相关问题
在图片上选边缘点以用来生成TSP art并输出tsplib数据集python代码
以下是一个简单的 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。
在图片上选点以用来生成TSP art的python代码
以下是一个简单的 Python 代码示例,用于选择图像上的点以生成 TSP 艺术:
```python
from PIL import Image
import random
def select_points(image_path, num_points):
# 打开图像
with Image.open(image_path) as img:
# 获得图像的宽和高
width, height = img.size
# 选择随机的点
points = []
for i in range(num_points):
x = random.randint(0, width-1)
y = random.randint(0, height-1)
color = img.getpixel((x, y))
points.append((x, y, color))
return points
```
该代码使用 Python 的 PIL 库来打开图像,并在图像上选择随机点。您需要提供图像路径和要选择的点的数量。该函数将返回一个列表,其中包含每个点的 x 和 y 坐标,以及该点的颜色。您可以使用此列表来生成 TSP 艺术。