def main(): parser = OptionParser(description="Circle generator for draw-fft p5js drawing web app.") parser.add_option("-i", "--image", dest="image_filename", help="Path to image to transform into circles. All bitmap file types are supported and vector images in SVG.") parser.add_option("-p", "--samples-count", type="int", default=1000, dest="samples_count", help="Number of samples extracted from input image") parser.add_option("-c", "--circles-count", type="int", default=100, dest="circles_count", help="Number of output circles (harmonics)") parser.add_option("-s", "--sample-scale", type="float", default=1.0, dest="sample_scale", help="Multiplication coefficient for x and y coordinates of given image)") parser.add_option("-a", "--amplitude-scale", type="float", default=1.0, dest="amplitude_scale", help="Multiplication coefficient for radius (amplitude) of circles") parser.add_option("-f", "--frequency-scale", type="float", default=1.0, dest="frequency_scale", help="Multiplication coefficient for frequency of circles") options, args = parser.parse_args() points = None if "svg" in options.image_filename.lower(): svg_paths, _ = svg2paths(options.image_filename) vector_path = path.concatpaths(svg_paths) time = np.linspace(0.0, 1.0, options.samples_count) points = np.asarray([vector_path.point(t) for t in time]).view(np.float).reshape(options.samples_count, 2) * options.sample_scale else: image = np.asarray(Image.open(options.image_filename).convert('L')) cloud = image_to_point_cloud(image, options.samples_count) path_indexes = solve_tsp(make_dist_matrix(cloud[0, :], cloud[1, :])) points = np.asarray(list(zip(cloud[0, path_indexes], cloud[1, path_indexes]))) * options.sample_scale circles_json = calculate_circles(points, scale=options.amplitude_scale, speed=options.frequency_scale, harmonics_length=options.circles_count) print(circles_json)
def main(*args): if image_link.startswith('http'): try: image_path = image_url.split('/')[-1] except Exception: image_path = 'Image.jpg' if not os.path.exists(image_path): print('Getting image from URL') urllib.urlretrieve(image_url, image_path) else: print('Loading image from local path') image_path = image_link original_image = Image.open(image_path) # Convert Original image to black and white. original_image = original_image.convert('L') w, h = original_image.width, original_image.height bw_image = original_image.convert('1', dither=Image.NONE) bw_image_array = np.array(bw_image, dtype=np.int) black_indices = np.argwhere(bw_image_array == 0) # Changing "size" to a larger value makes this algorithm take longer, # but provides more granularity to the portrait chosen_black_indices = black_indices[np.random.choice( black_indices.shape[0], replace=False, size=size)] fig = plt.figure(figsize=(w / 100 + 1, h / 100), dpi=110) plt.scatter([x[1] for x in chosen_black_indices], [x[0] for x in chosen_black_indices], color='black', s=1) plt.gca().invert_yaxis() plt.xticks([]) plt.yticks([]) print('Scatter image created') fig.savefig(image_path.replace('.jpg', '_scatter.png'), bbox_inches='tight', dpi=fig.dpi) print('Creating tsp image. Note: This will take time!!!') distances = pdist(chosen_black_indices) distance_matrix = squareform(distances) optimized_path = solve_tsp(distance_matrix) optimized_path_points = [chosen_black_indices[x] for x in optimized_path] plt.figure(figsize=((w / 100) + 2, (h / 100) + 2), dpi=100) plt.plot([x[1] for x in optimized_path_points], [x[0] for x in optimized_path_points], color='black', lw=1) plt.xlim(0, w) plt.ylim(0, h) plt.gca().invert_yaxis() plt.xticks([]) plt.yticks([]) plt.savefig('traveling-salesman-portrait.png', bbox_inches='tight')
def read_image_as_complex(image_file_path, num_indicies=1700, indices_step_size=5): """ Read image outline into complex numbers. Uses random num_indicies locations to create outline of image :param num_indicies The number of random indicies to select from the image outline :param indicies_step_size The step size to use for excluding indicies. Select higher value to reduce data size, DFT size, and computation time of epicycles, at the cost of drawing accuracy. :returns Image outline indices as complex numbers """ # Image drawing point extraction algorithm from Randy Olson: # http://www.randalolson.com/2018/04/11/traveling-salesman-portrait-in-python/ # Convert image to black and white image = Image.open(image_file_path, "r") bw_image = image.convert('1', dither=Image.NONE) #plt.imshow(bw_image) # Identify black pixels and select random subset of them bw_image_array = np.array(bw_image, dtype=np.int) black_indices = np.argwhere(bw_image_array == 0) chosen_black_indices = black_indices[np.random.choice( black_indices.shape[0], replace=False, size=num_indicies)] # Find path between black pixels by solving the Traveling Salesman Problem distances = pdist(chosen_black_indices) distance_matrix = squareform(distances) print("Solving traveling salesman problem for drawing path...") optimized_path = solve_tsp(distance_matrix) print("Done solving traveling salesman.") optimized_path_points = [ chosen_black_indices[x] for x in optimized_path ] # Plot the traveling salesman path of the points to draw """ plt.figure() plt.scatter([x[1] for x in chosen_black_indices], [x[0] for x in chosen_black_indices], color='red', s=1) plt.gca().invert_yaxis() plt.xticks([]) plt.yticks([]) """ # Save the black pixel path (x, y) coordinates as complex numbers z = [] for i in range(0, len(optimized_path_points), indices_step_size): z.append( complex(optimized_path_points[i][1], optimized_path_points[i][0])) return z
def solver(self, distance_matrix, chosen_black_indices): if not self.image_prepared: return t1 = time.time() optimized_path = solve_tsp(distance_matrix) t2 = time.time() self.time = t2 - t1 self.optimized_path_points = [ chosen_black_indices[x] for x in optimized_path ] print('solved in %.2f seconds' % self.time) self.mainWindow.actionOpenFile.setDisabled(False) return
def generate_itinerary(dispatch_list): # get the clinics involved: 0 represents the hospital t = [0] clinics = {} for orderUUID in dispatch_list: order = Order.objects.get(id=orderUUID) if order.clinic.id not in t: t.append(order.clinic.id) clinics[str(order.clinic.id)] = order.clinic # create distance matrix from t r = range(len(t)) d = numpy.zeros((len(t), len(t))) # return list name = ["Queen Mary Hospital Drone Port"] latitude = [22.270257] longitude = [114.131376] altitude = [161.00] # calculate distance matrix for i, a in enumerate(t): for j, b in enumerate(t): if i == 0 and j != 0: # i is hospital dist = DistanceClinicHospital.objects.filter(b__id = b).values('distance') d[i][j] = dist[0]['distance'] elif j == i: d[i][j] = 0 elif j == 0 and i != 0: # j is hospital dist = DistanceClinicHospital.objects.filter(b__id = a).values('distance') d[i][j] = dist[0]['distance'] else: dist = DistanceClinic.objects.filter(a__id = a, b__id = b).values('distance') d[i][j] = dist[0]['distance'] # append column and row d = numpy.insert(d,0,d[:,0],axis=1) d = numpy.insert(d,0,d[0],axis=0) # tsp solver sol = solve_tsp(d, endpoints = (0,1)) for clinic in sol: id = 0 if clinic > 1: id = t[clinic - 1] if id != 0: c = clinics[str(id)] s = str(c.latitude) + "," + str(c.longitude) + "," + str(c.altitude) name.insert(0,clinics[str(id)].name) latitude.insert(0,clinics[str(id)].latitude) longitude.insert(0,clinics[str(id)].longitude) altitude.insert(0,clinics[str(id)].altitude) return {'name': name, 'latitude': latitude, 'longitude': longitude, 'altitude':altitude}
def main(): from optparse import OptionParser parser = OptionParser( description= "Travelling Salesman Problem demo solver. Searches for a suboptimal solution of a given N-point problem" ) parser.add_option("-s", "--show-plot", action="store_true", default=False, dest="show_plot", help="Plot generated solution using PyPlot") parser.add_option( "-o", "--output", dest="output", help="Ouptut file to store path to. By default, saves nothing. " + "Data is in the Numpy format, single 2xN array of point coordinates") parser.add_option( "-p", "--pattern", dest="pattern", default="spot", help= "Pattern to show, one of [spot, ring, box, image:path]. The 'spot' generates round spot of points, distributed by Gaussian law. " + "The 'ring' produces a ring of points. " + "The 'box' produces uniformly filled rectangle. " + "The image:/path/to/image uses BW image, where black areas are filled with points" ) parser.add_option( "-n", "--num-points", type="int", default=500, dest="num_points", help= "Number of random points to generate, less than 5000 (actually, 3000 is a practical limit)" ) (options, args) = parser.parse_args() N = options.num_points if N < 2: parser.error("Need at least 2 points") if N > 5000: print( "Warning: probably, number of points is too big. Try below 5000.") IMAGE_PREFIX = "image:" if options.pattern == "spot": xy = spot_points(N) elif options.pattern == "ring": xy = ring_points(N) elif options.pattern == "box": xy = box_points(N) elif options.pattern.startswith(IMAGE_PREFIX): xy = image_points(N, options.pattern[len(IMAGE_PREFIX):]) else: print("Unknown pattern:%s" % (options.pattern)) exit(1) print("Solving sample TSP problem for %d points" % (N)) path = solve_tsp(make_dist_matrix(xy[0, :], xy[1, :])) print("Solved") if options.output: try: with open(options.output, "wb") as fl: np.save(fl, xy[:, path]) print("Saved file %s" % (options.output)) except IOError as err: print("IO exception:", err) exit(2) if options.show_plot or not options.output: try: import matplotlib.pyplot as pp except ImportError as err: print("Can't show plot, matplotlib module not available:", err) print("Either install matplotlib or set an -o option") exit(2) pp.plot(xy[0, path], xy[1, path], 'k-') pp.show()
def conf_mtr( results ): """ Build statistics of output data, y_org, y_rec are list of pairs: (y_reco, y_org) where y_reco/y_org are class indices """ y_org = np.array( [ org for (reco, org) in results ] ); y_reco = np.array( [ reco for (reco, org) in results ] ); out_size = len( y_org ); if ( out_size != len( y_reco ) ): return None; # build histogram of true classes class_cnt = int(np.max( y_org ) + 1); histo = np.zeros( (class_cnt,) ); for y in y_org: histo[y] = histo[y] + 1; histo = histo / np.sum( histo ); # create confusion matrix conf = np.zeros( (class_cnt, class_cnt ) ); for y_t,y_r in zip( y_org, y_reco ): conf[y_t,y_r] = conf[y_t,y_r] + 1.0; conf_t = np.copy( conf ); conf_t = np.transpose( conf_t); for i in range( class_cnt ): conf[i] = conf[i] / np.sum( conf[i] ); for i in range( class_cnt ): conf_t[i] = conf_t[i] / np.sum( conf_t[i] ); distance = np.zeros( (class_cnt, class_cnt ) ); for i in range( class_cnt ): for j in range( i, class_cnt ): if ( i == j ): distance[i,j] = 0.0 else: distance[i,j] = 1.0 - (conf[i,j] + conf[j,i] ) / 2.0; distance[j,i] = 1.0 - (conf[i,j] + conf[j,i] ) / 2.0; # Create phone reorder lookup table that can be used to reorder # phones. For convolutional NN it may be desired to have acoustically # similar phones in close neighborhood in features tensor. Traveling # salesman algorithm provides one of possible solution to this problem. path = greedy_numpy.solve_tsp( distance, optim_steps = 20 ) # get the vector of correct class recognitions true_rec = np.zeros( (class_cnt,) ); for i in range( len( conf ) ): true_rec[i] = conf[i,i]; # Find two most frequent recognitions for each true class conf_cpy = np.copy( conf ); max2 = [] for i in range( class_cnt ): j = np.argmax( conf_cpy[i] ); conf_cpy[i,j] = 0; j1 = np.argmax( conf_cpy[i] ); conf_cpy[i,j1] = 0; j2 = np.argmax( conf_cpy[i] ); max2.append( (j,j1,j2) ); return (histo, conf, conf_t, true_rec, max2, distance, path);
plt.figure(figsize=(6, 8), dpi=100) plt.scatter([x[1] for x in chosen_black_indices], [x[0] for x in chosen_black_indices], color='black', s=1) plt.gca().invert_yaxis() plt.xticks([]) plt.yticks([]) plt.savefig("tmp_first.png", bbox_inches='tight') ## distance between each pixels distances = pdist(chosen_black_indices) ##X * X matrix containing the distance between each and every pixels distance_matrix = squareform(distances) optimized_path = solve_tsp(distance_matrix) optimized_path_points = [chosen_black_indices[x] for x in optimized_path] plt.figure(figsize=(8, 10), dpi=100, frameon=False) plt.plot([x[1] for x in optimized_path_points], [x[0] for x in optimized_path_points], color='black', lw=1) plt.xlim(0, 600) plt.ylim(0, 800) #plt.gca().invert_yaxis() plt.xticks([]) plt.yticks([]) plt.axis('off') plt.savefig("tmp.png", bbox_inches='tight')
from scipy.spatial.distance import pdist, squareform image_url = 'http://ereaderbackgrounds.com/movies/bw/Frankenstein.jpg' image_path = 'Frankenstein.jpg' if not os.path.exists(image_path): urllib.request.urlretrieve(image_url, image_path) original_image = Image.open(image_path) bw_image = original_image.convert('1', dither=Image.NONE) bw_image_array = np.array(bw_image, dtype=np.int) black_indices = np.argwhere(bw_image_array == 0) chosen_black_indices = black_indices[np.random.choice(black_indices.shape[0], replace=False, size=10000)] distances = pdist(chosen_black_indices) distance_matrix = squareform(distances) optimized_path = solve_tsp(distance_matrix) optimized_path_points = [chosen_black_indices[x] for x in optimized_path] plt.figure(figsize=(8, 10), dpi=100) plt.plot([x[1] for x in optimized_path_points], [x[0] for x in optimized_path_points], color='black', lw=1) plt.xlim(0, 600) plt.ylim(0, 800) plt.gca().invert_yaxis() plt.xticks([]) plt.yticks([]) plt.savefig('traveling-salesman-portrait.png', bbox_inches='tight')
x = pts_p % x_size y = pts_p / x_size points = np.vstack((x,y)) #Scale point coordinates into physical range y_range = float(y_size) / float(x_size) * x_range points = points.astype('float') points[0] = points[0] * (x_range / x_size) - x_range / 2 points[1] = -(points[1] * (y_range / y_size) - y_range / 2) #### Solve travelling salesman problem for optimal trajectory # Make symmetric distance matrix from points dist_matrix = squareform(pdist(points.T)) path = solve_tsp(dist_matrix) #Reorder points according to optimal path points = points.T[path] #### Make trajectory and write it to file dt = 0.01 #sec time_for_point = 2 #sec total_time = time_for_point * N_pts num_rec = int(total_time / dt) # Y coordinate is constant y_t = 80 * np.ones((num_rec)) x_t = np.array([])
boxes.append([xf-d,yf-d,xf+d,yf+d]) D = [] for i in range(len(boxes)): d = [] f = boxes[i] x0 = (f[0]+f[2])/2 y0 = (f[1]+f[3])/2 for j in range(i): g = boxes[j] x1 = (g[0]+g[2])/2 y1 = (g[1]+g[3])/2 d.append(math.sqrt((x0-x1)**2+((y0-y1)*4)**2)) D.append(d) path = solve_tsp(D) faces = [boxes[p] for p in path] #cv2.imshow('',im) #cv2.waitKey(0) #cv2.imshow('',(im.astype('float32')/255.0)*(cv2.resize(sal[idx],(im.shape[1],im.shape[0])).astype('float32')/255.0)) #cv2.waitKey(0) #cv2.imshow('',(im2.astype('float32')/255.0)*(cv2.resize(sal[idx],(im2.shape[1],im2.shape[0])).astype('float32')/255.0)) #cv2.waitKey(0) for f in faces: # print([W,H,f['box']])
def main(): from optparse import OptionParser parser = OptionParser( description = "Travelling Salesman Problem demo solver. Searches for a suboptimal solution of a given N-point problem" ) parser.add_option( "-s", "--show-plot", action = "store_true", default=False, dest="show_plot", help="Plot generated solution using PyPlot" ) parser.add_option( "-o", "--output", dest="output", help="Ouptut file to store path to. By default, saves nothing. "+ "Data is in the Numpy format, single 2xN array of point coordinates" ) parser.add_option( "-p", "--pattern", dest="pattern", default="spot", help="Pattern to show, one of [spot, ring, box, image:path]. The 'spot' generates round spot of points, distributed by Gaussian law. "+ "The 'ring' produces a ring of points. "+ "The 'box' produces uniformly filled rectangle. "+ "The image:/path/to/image uses BW image, where black areas are filled with points" ) parser.add_option( "-n", "--num-points", type="int", default=500, dest="num_points", help="Number of random points to generate, less than 5000 (actually, 3000 is a practical limit)" ) (options, args) = parser.parse_args() N = options.num_points if N < 2: parser.error ("Need at least 2 points") if N > 5000: print ("Warning: probably, number of points is too big. Try below 5000.") IMAGE_PREFIX = "image:" if options.pattern == "spot": xy = spot_points( N ) elif options.pattern == "ring": xy = ring_points( N ) elif options.pattern == "box": xy = box_points( N ) elif options.pattern.startswith(IMAGE_PREFIX): xy = image_points(N, options.pattern[len(IMAGE_PREFIX):]) else: print ("Unknown pattern:%s"%(options.pattern)) exit(1) print ("Solving sample TSP problem for %d points"%(N)) path = solve_tsp( make_dist_matrix(xy[0,:],xy[1,:]) ) print ("Solved") if options.output: try: with file( options.output, "w") as fl: np.save( fl, xy[:,path]) print ("Saved file %s"%(options.output)) except IOError as err: print ("IO exception:", err) exit(2) if options.show_plot or not options.output: try: import matplotlib.pyplot as pp except ImportError as err: print ("Can't show plot, matplotlib module not available:", err) print ("Either install matplotlib or set an -o option" ) exit(2) pp.plot( xy[0,path], xy[1,path], 'k-' ) pp.show()