|  | 
| 16 | 16 | import numpy as np | 
| 17 | 17 | import urllib.request | 
| 18 | 18 | from PIL import Image | 
| 19 |  | -from itertools import combinations | 
| 20 | 19 | from tsp_solver.greedy_numpy import solve_tsp | 
|  | 20 | +from scipy.spatial.distance import pdist, squareform | 
| 21 | 21 | 
 | 
| 22 | 22 | image_url = 'http://ereaderbackgrounds.com/movies/bw/Frankenstein.jpg' | 
| 23 | 23 | image_path = 'Frankenstein.jpg' | 
|  | 
| 32 | 32 | black_indices = np.argwhere(bw_image_array == 0) | 
| 33 | 33 | chosen_black_indices = black_indices[np.random.choice(black_indices.shape[0], replace=False, size=10000)] | 
| 34 | 34 | 
 | 
| 35 |  | -distance_lookup = {} | 
| 36 |  | - | 
| 37 |  | -for (p1, p2) in combinations(range(len(chosen_black_indices)), r=2): | 
| 38 |  | - p1 = tuple(chosen_black_indices[p1]) | 
| 39 |  | - p2 = tuple(chosen_black_indices[p2]) | 
| 40 |  | - x1, y1 = p1 | 
| 41 |  | - x2, y2 = p2 | 
| 42 |  | - distance_lookup[(p1, p2)] = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) | 
| 43 |  | -  | 
| 44 |  | -distance_matrix = [] | 
| 45 |  | -for row_num in range(0, len(chosen_black_indices)): | 
| 46 |  | - row_list = [] | 
| 47 |  | - for col_num in range(0, row_num): | 
| 48 |  | - p1 = tuple(chosen_black_indices[row_num]) | 
| 49 |  | - p2 = tuple(chosen_black_indices[col_num]) | 
| 50 |  | - if (p1, p2) in distance_lookup: | 
| 51 |  | - row_list.append(distance_lookup[p1, p2]) | 
| 52 |  | - else: | 
| 53 |  | - row_list.append(distance_lookup[p2, p1]) | 
| 54 |  | - distance_matrix.append(row_list) | 
|  | 35 | +distances = pdist(chosen_black_indices) | 
|  | 36 | +distance_matrix = squareform(distances) | 
| 55 | 37 | 
 | 
| 56 | 38 | optimized_path = solve_tsp(distance_matrix) | 
| 57 | 39 | 
 | 
|  | 
0 commit comments