Exemplo n.º 1
0
def display_view(path, index, newfig=False):
    if newfig:
        plt.figure(index)
    ax = plt.gca()
    plt.imshow(island.transpose())
    color_step = 255 / len(path.path())
    color = [color_step, color_step, color_step]
    i = 0
    for mvs in path.toMultipleDf():
        rdm = mvs[0]
        drt = mvs[1]
        rdm = geo.reduce_path(rdm, mc.REDUCTION_RADIUS)
        drt = geo.reduce_path(drt, mc.REDUCTION_RADIUS)
        orig = mvs[1].iloc[0]
        dest = mvs[1].iloc[-1]
        view = mvs[1].iloc[0]
        plt.axis('scaled')
        plt.scatter(orig.x, orig.y, s=50, c="#0000FF")
        plt.scatter(dest.x, dest.y, s=50, c="#FF0000")
        plt.scatter(view.x, view.y, s=50, c="#00FF00")
        plt.plot(rdm.x,
                 rdm.y,
                 c=rgb2hex(int(color[0]), int(color[1]), int(color[2])))
        plt.plot(drt.x, drt.y, c=rgb2hex(int(color[0]), 0, 0))
        color[0] = color[0] + color_step
        color[1] = color[1] + color_step
        color[2] = color[2] + color_step
        i += 1
    for f in fruits:
        c = plt.Circle((f.x, f.y), radius=7, color="#FFFFFF")
        ax.add_patch(c)
    plt.draw()
Exemplo n.º 2
0
def color_picker(url):
    url=url.replace(' ','%20')
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)

    anr = (image[:100,:,0]).flatten()#B
    anr_dom = np.bincount(anr).argmax()
    # print(anr_dom)

    ang = (image[:100,:,1]).flatten()#G
    ang_dom = np.bincount(ang).argmax()

    anb = (image[:100,:,2]).flatten()#R
    anb_dom = np.bincount(anb).argmax()

    data = np.reshape(image, (-1,3))
    data = np.float32(data)

    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    flags = cv2.KMEANS_RANDOM_CENTERS
    compactness,labels,centers = cv2.kmeans(data,1,None,criteria,10,flags)

    bgr = centers[0].astype(np.int32)



    result = {
        'logo_border': rgb2hex(int(anb_dom),int(ang_dom),int(anr_dom)),
        'dominant_color': rgb2hex(bgr[2],bgr[1],bgr[0])
    }

    # return url

    return jsonify(result)
Exemplo n.º 3
0
def color(code):
    letter = code[0]
    if len(code) > 1:
        number = code[1:]

        if letter == 'S':
            if number == '0':
                return "red"
            if number == '1':
                return "blue"
        if letter == 'P':
            if number == '0':
                return "indian red"
            if number == '1':
                return "steel blue"
        if letter == 'G':
            if number == '0':
                return "red4"
            if number == '1':
                return "blue4"
        if letter == 'T':
            return rgb2hex(130 + int(number) * 20, int(number) * 40, 255)
        if letter == 'O':
            return rgb2hex(190, 190, 190)

    color = {
        'N': "white",
        'W': "black",
        'B': "green",
        'D': "gray",
        'K': "orange",
    }
    return color[letter]
Exemplo n.º 4
0
def getColours(width, height, im):
    # Pixel Count
    pixel_count = width * height
    processed_count = 0
    my_dict = defaultdict(int)
    for x in range(width):
        for y in range(height):
            r, g, b = im.getpixel((x, y))
            # Convert RGB to Hex
            red = int(math.ceil(r / 40.0)) * 40
            green = int(math.ceil(g / 40.0)) * 40
            blue = int(math.ceil(b / 40.0)) * 40

            if red > 255:
                red = 255
            if green > 255:
                green = 255
            if blue > 255:
                blue = 255

            hexColor = rgb2hex(red, green, blue)
            # Append Hex Colour to List
            hexList.append(hexColor)
            if hexColor in my_dict:
                my_dict[hexColor] += 1
            else:
                my_dict[hexColor] = 1

            processed_count += 1

            print("Processed " + str(processed_count) + " Out of " + str(pixel_count))

    findCommonColours(my_dict, im)
Exemplo n.º 5
0
def findDominatColor(path):

    NUM_CLUSTERS = 5

    print('reading image')
    im = Image.open(path)
    im = im.resize((150, 150))  # optional, to reduce time
    # ar = np.asarray(im)
    ar = scipy.misc.fromimage(im)
    shape = ar.shape
    ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)

    print('finding clusters')
    codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
    print('cluster centres:\n', codes)

    vecs, dist = scipy.cluster.vq.vq(ar, codes)  # assign codes
    counts, bins = scipy.histogram(vecs, len(codes))  # count occurrences

    index_max = scipy.argmax(counts)  # find most frequent
    peak = codes[index_max]
    # colour = ''.join(chr(int(c)) for c in peak).encode('hex')
    colour = ''.join(chr(int(c)) for c in peak).encode()
    # colour = bytes(colour, "utf-8")
    colour = encode(colour, "hex")

    # my way to convert rgb to hex
    colour = rgb2hex(int(peak[0]), int(peak[1]), int(peak[2]))

    print('most frequent is %s (#%s)' % (peak, str(colour)))
Exemplo n.º 6
0
 def get_dominant_colors(self):
     '''
     Gets the 5 most popular colors.
     '''
     color_frequencies = defaultdict(int)
     color_weights = defaultdict(int)
     gen1 = (self.color_helper(p, color_weights, color_frequencies)
             for p in self.posts if p.image_url != '')
     while True:
         try:
             next(gen1)
         except StopIteration:
             break
     gen2 = (self.color_wt_helper(color_weights, color_frequencies, k)
             for k in color_weights.keys())
     while True:
         try:
             next(gen2)
         except StopIteration:
             break
     sorted_colors = sorted(color_weights.items(),
                            key=operator.itemgetter(1))
     return [
         colormap.rgb2hex(c[0][0], c[0][1], c[0][2])
         for c in sorted_colors[-1:-6:-1]
     ]
def get_hex(num_clusters, img):
    """return the dominant hex code for an image"""

    # https://stackoverflow.com/questions/3241929/python-find-dominant-most-common-color-in-an-image/3242290
    np.random.seed(42)
    # turn image into numpy array
    ar = np.asarray(img)
    # (num_row, num_column, num_colors)
    shape = ar.shape
    # (num_pixel, num_color)
    ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)

    # create center for each color cluster, in the number of clusters specified in the param
    codes, dist = scipy.cluster.vq.kmeans(ar, num_clusters)

    # determine the which pixel belongs to which cluster based on the distance
    # between the pixel and the culster center
    vecs, dist = scipy.cluster.vq.vq(ar, codes)

    # gives us the number of pixels that belong in each cluster
    counts, bins = scipy.histogram(vecs, num_clusters)

    # find the index of the cluster that has the most pixels
    index_max = scipy.argmax(counts)

    # find which cluster is at that index
    peak = codes[index_max]

    return rgb2hex(int(peak[0]), int(peak[1]), int(peak[2]))
Exemplo n.º 8
0
def draw(canvas, labels, img):
    for label in labels:
        if (int(label[0]) + int(label[1]) + int(label[2]) == 0):
            continue
        if (255 - int(label[0]) + 255 - int(label[1]) + 255 - int(label[2]) <
                126):
            continue
        lo = np.array(label)
        hi = np.array(label)
        imgc = img.copy()
        mask = cv2.inRange(imgc, lo, hi)
        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_NONE)
        for contour in contours:
            area = cv2.contourArea(contour)
            #if(label[0] != img[x][y][0] or label[1] != img[x][y][1] or label[2] != img[x][y][2]):
            #    continue
            if (area > 100):
                contour_th = []
                i = 0
                while (i < len(contour)):
                    contour_th.append(tuple(contour[i][0]))
                    i = i + 1
                contour_th = reduce(contour_th)
                canvas.create_polygon(contour_th,
                                      fill=rgb2hex(label[0], label[1],
                                                   label[2]),
                                      outline='black',
                                      width=2,
                                      stipple='gray50',
                                      tag="polygon")
def vis_pcloud_interactive(res, img):
    import k3d
    from colormap import rgb2hex
    color_vals = np.zeros((img.shape[0], img.shape[1]))
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            color_vals[i, j] = int(
                rgb2hex(img[i, j, 0], img[i, j, 1],
                        img[i, j, 2]).replace('#', '0x'), 0)
    colors = color_vals.flatten()

    points = np.stack(
        (res['X'].flatten(), res['Y'].flatten(), res['Z'].flatten()), axis=1)

    invalid_inds = np.any(np.isnan(points), axis=1)
    points_valid = points[invalid_inds == False]
    colors_valid = colors[invalid_inds == False]
    plot = k3d.plot(grid_auto_fit=True, camera_auto_fit=False)
    plot += k3d.points(points_valid,
                       colors_valid,
                       point_size=0.01,
                       compression_level=9,
                       shader='flat')
    plot.display()
    plot.camera = [
        -0.3568942548181382, -0.12775125650240726, 3.5390732533009452,
        0.33508163690567017, 0.3904658555984497, -0.0499117374420166,
        0.11033077266672488, 0.9696364582197756, 0.2182481603445357
    ]
    return plot
def get_colors(img: Image) -> dict:
    '''Getting RGB colors from strange PIL palette.'''

    width, height = img.size
    dict_num = dict(img.getcolors(width * height))
    dict_rgb = dict(img.convert('RGB').getcolors(width * height))
    return {str(dict_num[key]): rgb2hex(*dict_rgb[key]) for key in dict_rgb}
Exemplo n.º 11
0
	async def role(self, ctx, *, role: Role = None):
		if not role:
			role = ctx.author.top_role
		embed = discord.Embed(colour=role.color if role.color != discord.Color.default() else ctx.author.color, timestamp=datetime.datetime.now(datetime.timezone.utc))
		embed.add_field(name="» Name", value=role.name, inline=False)
		embed.add_field(name="» ID", value=role.id, inline=False)
		embed.add_field(name="» Mention", value=f'`{role.mention}`', inline=False)
		rgbcolor = role.color.to_rgb()
		hexcolor = rgb2hex(role.color.r, role.color.g, role.color.b).replace('##', '#')
		embed.add_field(name="» Hoisted?", value='Yes' if role.hoist else 'No')
		embed.add_field(name="» Mentionable?", value='Yes' if role.mentionable else 'No')
		embed.add_field(name="» Color", value=f'RGB: {rgbcolor}\nHEX: {hexcolor}')
		perms = []
		if not role.permissions.administrator:
			for perm, value in role.permissions:
				if value and perm in permissions:
					perms.append(permissions[perm])
			if perms:
				embed.add_field(name="» Key Permissions", value=', '.join(perms), inline=False)
		else:
			embed.add_field(name="» Permissions", value='Administrator', inline=False)
		await ctx.send(embed=embed)
		is_cached = len(ctx.guild.members) / ctx.guild.member_count
		if role.members and is_cached > 0.98:
			paginator = WrappedPaginator(prefix='', suffix='', max_size=250)
			for member in role.members:
				paginator.add_line(member.mention)
			membed = discord.Embed(
				colour=role.color if role.color != discord.Color.default() else ctx.author.color,
				timestamp=datetime.datetime.now(datetime.timezone.utc),
				title=f'Members [{len(role.members):,d}]'
			)
			interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=membed)
			await interface.send_to(ctx)
Exemplo n.º 12
0
def upload_image():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        try:
            number_of_colors = int(request.form['number_of_colors'])
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            img = Image.open('static/uploads/' + filename, 'r').convert('RGB')
            if number_of_colors <= len(palette(img)[0]):
                top_colors = palette(img)[0][:number_of_colors]
                percent_of_colors = palette(img)[1][:number_of_colors]
                top_colors = [rgb2hex(color[0], color[1], color[2]) for color in top_colors]
                return render_template('upload.html', filename=filename, top_colors=top_colors, top_percents=percent_of_colors)
            else:
                flash('Wrong number of colors.')
                return redirect(request.url)
        except ValueError:
            flash('You have to type number')
            return redirect(request.url)
    else:
        flash('Allowed image types are -> png, jpg, jpeg, gif')
        return redirect(request.url)
Exemplo n.º 13
0
def avgColor(color1, color2):
    n = 2
    color1 = [(color1[i:i + n]) for i in range(0, len(color1), n)]
    color2 = [(color2[i:i + n]) for i in range(0, len(color2), n)]

    red1 = color1[0]
    red2 = color2[0]

    green1 = color1[1]
    green2 = color2[1]

    blue1 = color1[2]
    blue2 = color2[2]

    avg_red = int((int(red1, 16) + int(red2, 16)) / 2)
    avg_green = int((int(green1, 16) + int(green2, 16)) / 2)
    ava_blue = int((int(blue1, 16) + int(blue2, 16)) / 2)

    avg_color = rgb2hex(avg_red, avg_green, ava_blue)

    # hex_red = hex(avg_red)
    # hex_green = hex(avg_green)
    # hex_blue = hex(ava_blue)

    # avg_color = hex_red + hex_green + hex_blue

    return avg_color
Exemplo n.º 14
0
def import_json_colormap(input_f, directory='', cmap_name='imported_cmap'):
    filename = os.path.join(directory, input_f)
    with open(filename, 'r') as f:
        colors = json.load(f)
    colors = colors[0]['RGBPoints']  # extract the points and rgb colours
    rgb = np.array(colors).reshape(int(len(colors) / 4), 4)
    points = (rgb[:, 0] - rgb[0][0]) / (rgb[-1][0] - rgb[0][0]
                                        )  # normalise between 0 and 1
    hexcolors = [''] * len(rgb)
    ph = []
    for i in range(
            len(hexcolors)
    ):  # Convert rgb to hex and put into a list of tuples (point, hexcolor)
        r = int(rgb[i, 1] * 255)
        g = int(rgb[i, 2] * 255)
        b = int(rgb[i, 3] * 255)
        hexcolors[i] = rgb2hex(r, g, b)
        tup = (points[i], hexcolors[i])
        ph.append(tup)

    cmap = clr.LinearSegmentedColormap.from_list(cmap_name, ph, N=256)
    return cmap


## Example use:
# filename = 'test.json'
# cmap_name = 'new_cmap'
# new_cmap = import_json_colormap(filename, cmap_name)
Exemplo n.º 15
0
def recolor(namedColorsFilename, svgFilename, inputColors, referenceColors,
            matchingList):

    paletteDict = get_palette_from_svg(namedColorsFilename, svgFilename)

    numColors = inputColors.shape[0]

    replaceColorDict = {
    }  #will store the mapping of colors from input image to reference image

    for key, value in paletteDict.items():
        color_flag = False
        min_distance = colorDistance + 1
        min_index = -1
        for i in range(numColors):
            distance = np.sum(np.abs(np.array(value) - inputColors[i, :]))

            if distance < colorDistance:
                # print('****')
                if min_distance > distance:
                    min_distance = distance
                    min_index = i
                color_flag = True

        if color_flag:
            replaceWith = referenceColors[matchingList[min_index], :]
            hexcode = rgb2hex(int(replaceWith[0]), int(replaceWith[1]),
                              int(replaceWith[2]))
            replaceColorDict[key] = hexcode

    recoloredSVG = createRecoloredSvg(svgFilename, replaceColorDict)
    return recoloredSVG
Exemplo n.º 16
0
def activationInColor(i, min, max):
    act = (i - min) / (max - min)
    final = (255, 0, 0)
    initial = (168, 252, 100)
    return rgb2hex(int(final[0] * act + initial[0] * (1 - act)),
                   int(final[1] * act + initial[1] * (1 - act)),
                   int(final[2] * act + initial[2] * (1 - act)))
def get_main_color(centroid_color):       # 가장 많은 비율 차지하는 색깔 추출
    main_color = centroid_color
    R = int(main_color[0])              #RGB 값을 정수로 변환
    G = int(main_color[1])
    B = int(main_color[2])
    main_color = [R,G,B]             #정수로 변환한 RGB값
    hex_color = rgb2hex(int(R),int(G),int(B))   #rgb2hex(R,G,B) : rgb 색상 ---> hex(16진수코드) 색상으로 변환해주는 colormap 라이브러리 함수.

    return main_color, hex_color
def plot_colors(hist, centroids):
    # initialize the bar chart representing the relative frequency
    # of each of the colors
    bar = np.zeros((50, 300, 3), dtype="uint8")
    startX = 0
    hist, centroids = zip(*sorted(zip(hist, centroids), reverse=True))
    dist2white = np.array([])
    hexColor = np.array([])
    white_color = np.array([255, 255, 255])

    # loop over the percentage of each cluster and the color of
    # each cluster
    for (percent, color) in zip(hist, centroids):
        # plot the relative percentage of each cluster
        endX = startX + (percent * 300)
        int_color_np = color.astype("uint8")
        hex_color = rgb2hex(int_color_np[0], int_color_np[1], int_color_np[2])
        hexColor = np.append(hexColor, hex_color)
        dist = np.linalg.norm(white_color - int_color_np)
        dist2white = np.append(dist2white, dist.astype('uint32'))

        print(f"color {hex_color} is {percent} dist = {dist.astype('uint32')}")
        cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
                      color.astype("uint8").tolist(), -1)
        startX = endX
    # return the bar chart

    #sort by distance to white color, descending
    dist2white, hist, centroids, hexColor = zip(
        *sorted(zip(dist2white, hist, centroids, hexColor), reverse=True))

    print(f'distance = {dist2white}\n')
    print(f'hist = {hist}\n')
    print(f'centroids = {centroids}\n')
    print(f'hexColor = {hexColor}\n')

    colorCount = len(centroids)

    if colorCount == 0:
        primaryColor = secondaryColor = '#000000'
    else:
        if colorCount == 2:
            primaryColor = secondaryColor = hexColor[0]
        else:
            dist2white = np.delete(dist2white, colorCount - 1)
            hist = np.delete(hist, colorCount - 1)
            hexColor = np.delete(hexColor, colorCount - 1)
            # centroids.delete(colorCount - 1)

            hist, hexColor = zip(*sorted(zip(hist, hexColor), reverse=True))

            primaryColor = hexColor[0]
            secondaryColor = hexColor[1]

    print(f'Primary color = {primaryColor}\n')
    print(f'Secondary color = {secondaryColor}\n')
    return bar
Exemplo n.º 19
0
def get_colour_name(rgb):
    requested_colour = (rgb.r, rgb.g, rgb.b)
    hex_code = rgb2hex(rgb.r, rgb.g, rgb.b)
    try:
        closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
    except ValueError:
        closest_name = closest_colour(requested_colour)
        actual_name = None
    return actual_name, closest_name, hex_code
Exemplo n.º 20
0
    def generate_map(self, filename):
        if filename == "levels/welcome_screen":
            return [HomeScreen(self.WIDTH / 2, self.HEIGHT / 2)]

        object_array = []
        try:
            map = Image.open(filename)

        except IOError:
            print("Unable to load image")
            sys.exit(1)

        pixel_matrix = self.generate_pixel_array(map.size[0])
        rgb_map = map.convert("RGB")

        for column in range(
                map.size[0]
        ):  # iterate through and find the index of the player. Used to calculate relative positions
            for row in range(map.size[1]):
                r, g, b = rgb_map.getpixel((row, column))
                hexval = rgb2hex(r, g, b)
                if hexval.lower() == "#00e9e5":
                    self.player_pos = (row, column)
                    self.PLAYER = self.object_type(hexval, (row, column))
                    #object_array.append(self.PLAYER)
                    break  # break for efficiency

        for column in range(
                map.size[0]):  # yay we're iterating again this seems efficient
            for row in range(map.size[1]):
                r, g, b = rgb_map.getpixel((row, column))
                pixel_matrix[row][column] = True
                if r != 255 or g != 255 or b != 255:
                    hexval = rgb2hex(r, g, b)
                    object_to_add = self.object_type(hexval, (row, column))

                    if object_to_add is not None:
                        object_array.append(object_to_add)
                        self.final_array.append(
                            object_to_add
                        )  # allows us to update positions of everything except excalibur
        self.update_positions
        return object_array
Exemplo n.º 21
0
async def dominant_color(link):

    response = requests.get(link)
    data = BytesIO(response.content)
    color_thief = ColorThief(data)
    dc = color_thief.get_color(quality=1)    
    hex = rgb2hex(dc[0], dc[1], dc[2])

    return hex
    
Exemplo n.º 22
0
    async def dominant(self, ctx, user: discord.Member = None):
        if user is None:
            user = ctx.author

        asset = user.avatar_url_as(size=256)
        data = BytesIO(await asset.read())
        color_thief = ColorThief(data)
        dc = color_thief.get_color(quality=1)
        hex = rgb2hex(dc[0], dc[1], dc[2])

        await ctx.send(hex)
Exemplo n.º 23
0
def swim_plot(x, y, z, colors):
    #Change the size of the points plotted here
    pointsize = 20

    #Change this to plot every x points
    #Example: set as 5 to plot every 5th point, or set as 1 to plot every point
    plot_every_x = 2

    #Change the color threshold here (0-255 scale)
    #points with color below this value will not be plotted
    color_threshold = 20

    #Set up the progress bar
    bar = progressbar.ProgressBar().start()
    bar.maxval = 101

    if (sys.argv[2]):
        figname = sys.argv[2]
    else:
        figname = "swim_plot.png"

    fig = plt.figure()
    ax = Axes3D(fig)

    #Normalize the colors to range(0-255)
    #Note that for efficiency only the points being used based on the plot_every_x
    #parameter are sent for normalization
    colors = normalize_255(colors[::plot_every_x])

    print("Plotting figure...")

    if not (plot_every_x == 1):
        print('Note: plotting one in every %d points' % plot_every_x)
        print("To change this, edit the plot_every_x parameter")

    one_percent_progress = int(len(y) / 100)
    bar_val = 0
    j = 0

    for i in range(len(y))[::plot_every_x]:
        if (True):
            if (colors[j] > color_threshold):
                hexcolor = rgb2hex(0, int(colors[j]), 0)
                ax.scatter(x[i], y[i], z[i], s=pointsize, color=hexcolor)
            j += 1
        if not (i % one_percent_progress):
            bar_val += 1
            bar.update(bar_val)

    plt.show()
    fig.savefig(figname)
    print("Figure saved as %s") % figname
    plt.close(fig)
def get_colors(file_name):

    color_thief = ColorThief(file_name)

    palette = color_thief.get_palette(color_count=6)

    colors = []

    for p in palette:
        colors.append(rgb2hex(p[0], p[1], p[2]))

    return colors
Exemplo n.º 25
0
    def fade(self):
        from colormap import rgb2hex

        red = self.color.get_red() * 255
        red = int(round(red - (red * .3)))
        green = self.color.get_green() * 255
        green = int(round(green - (green * .3)))
        blue = self.color.get_blue() * 255
        blue = int(round(blue - (blue * .3)))

        self.set_color(rgb2hex(red, green, blue))
        return self
Exemplo n.º 26
0
 def show_video(self):
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.connect((self.ip, self.port))
     for image in self.images:
         for counter, y_ in enumerate(image):
             for counter2, x_ in enumerate(y_):
                 hex_color = rgb2hex(x_[2], x_[1], x_[0])
                 hex_color = hex_color.replace("#", "")
                 message = "CC {0} {1} {2}\n".format(
                     self.x + counter2, self.y + counter, hex_color)
                 s.send(str.encode(message))
     s.close()
Exemplo n.º 27
0
 def getMap(self):
     map = []
     if self.getpgpic() != None:
         im = Image.open(self.getpgpic())
         rgpim = im.convert('RGB')
         width, height = im.size
         print(width, height)
         for y in range(height):
             for x in range(width):
                 r, g, p = rgpim.getpixel((x, y))
                 map.append(rgb2hex(r, g, p))
         return map
Exemplo n.º 28
0
    def drawDoors(self, canvas):

        if self.doors:
            for door in self.doors:
                color = np.random.randint(0, 255, (3)).tolist()
                radius = 3
                x, y, w, h = door.boundBox
                x1 = int(x / self.ratio)
                y1 = int(y / self.ratio)
                x2 = int((w) / self.ratio)
                y2 = int((h) / self.ratio)
                canvas.create_rectangle(x1,
                                        y1,
                                        x1 + x2,
                                        y1 + y2,
                                        activefill=rgb2hex(*color),
                                        stipple="gray50")
                if door.keypoints:
                    for ind, keypoint in enumerate(door.keypoints):
                        x, y, label = keypoint
                        pointx = int(x / self.ratio)
                        pointy = int(y / self.ratio)
                        label_colors = ['']
                        label_colors.extend(
                            [color['color'] for color in self.labels])

                        point = canvas.create_oval(pointx - radius,
                                                   pointy - radius,
                                                   pointx + radius,
                                                   pointy + radius,
                                                   fill=label_colors[label],
                                                   tags='points',
                                                   activefill=rgb2hex(*color),
                                                   outline="")
                        canvas.tag_bind(
                            point,
                            "<Button-1>",
                            lambda event, ind=ind: self.show_options(
                                event, [canvas, door.ids, ind]))
                self.draw_lines(canvas)
Exemplo n.º 29
0
 def load_new_list(self):
     self.lb.delete('0', 'end')
     dic_name = askopenfilename(parent=self.window,
                                initialdir=os.getcwd(),
                                title="Select file",
                                defaultextension="*.h5",
                                filetypes=[("H5 file", "*.h5")])
     if (dic_name == ""):
         return
     with open(dic_name, 'rb') as f:
         self.list = pickle.load(f)
     for key in self.list.keys():
         self.list[key] = [self.list[key][0], self.lb.size()]
         self.lb.insert("end", key)
         self.lb.itemconfig(self.lb.size() - 1,
                            bg=rgb2hex(self.list[key][0][0],
                                       self.list[key][0][1],
                                       self.list[key][0][2]))
         self.lb.itemconfig(self.lb.size() - 1,
                            foreground=rgb2hex(255 - self.list[key][0][0],
                                               255 - self.list[key][0][1],
                                               255 - self.list[key][0][2]))
Exemplo n.º 30
0
 def update(self, data):
     print(data)
     self.hex = rgb2hex(data[0][0], data[0][1], data[0][2])
     self.bw.config(bg=self.hex)
     self.bb.config(bg=self.hex)
     txt = 'Confidence: ' + str(data[1])
     self.c.itemconfigure(self.confidence, text=txt)
     if data[2] == 1 and self.guess == 0:
         self.c.move(self.guess_oval, -200, 0)
         self.guess = 1
     elif data[2] == 0 and self.guess == 1:
         self.c.move(self.guess_oval, 200, 0)
         self.guess = 0
Exemplo n.º 31
0
def output():
  	string = request.args.get('style1')
	style1 = list_style.index(string)
	print style1
        tileset = r'http://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.png'
        attribution = 'Map data by OpenStreetMap, under ODbL.'
        map = folium.Map(location=[37.426327,-122.141076],zoom_start=2, tiles=tileset, 
                     attr=attribution)
  	with db:
    		cur = db.cursor()
		cur.execute("SELECT lat,lon,url,user, style1,sval1 FROM New_Flickr_info WHERE style1='%s' AND sval1>.7;" % style1)
    		query_results = cur.fetchall()

  	lat = []
	lon = []
	url = []
	user = []
	s= []
        for result in query_results:
		lat.append(result[0])
		lon.append(result[1])
		url.append(result[2])
		user.append(result[3])
		s.append(result[4])

	mydata = pd.DataFrame(lat, columns=['lat'])
	mydata['lon'] = lon
	mydata['url'] = url
	mydata['user'] = user
	mydata['style1']=s

	for _, df in mydata.iterrows():
		color = rgb2hex(*plt.cm.Spectral(df['style1']/20))
		map.circle_marker(
			location=[df['lat'], df['lon']],
			popup='<img src={url} width=200 height=200> <br> {style}'.format(url=df['url'], style=list_style[df['style1']]),
			fill_color=color,
			line_color=color,
			radius=40,
			)
	map.create_map(path='/Users/wolk/Desktop/Insight/Myapp/app/templates/osm.html')
	return render_template('osm.html')
Exemplo n.º 32
0
            blue = random.randint(0,255)
            brightness = 200
            green  = max(0,min( 255,brightness - int((0.2126 *red +  0.0722 *blue)/0.7152 )))

        red_bk = max(red-100,0)
        blue_bk = max(blue-100,0)
        green_bk = max(green-100,0)

        print red,blue,green
        for node in node_set:
            g.node[node]['normpos'] = g.node[node]['chr'] * max_chr_multiplier + (g.node[node]['aln_end']/float(max_chr_len))*max_chr_multiplier
            lamda = (g.node[node]['aln_end']/max_chr_len)
            nd_red = (1-lamda)*red + lamda*red_bk
            nd_green = (1-lamda)*green + lamda*green_bk
            nd_blue = (1-lamda)*blue + lamda*blue_bk
            g.node[node]['color'] = rgb2hex(nd_red, nd_green, nd_blue)
            g.node[node]['color_r'] = nd_red
            g.node[node]['color_g'] = nd_green
            g.node[node]['color_b'] = nd_blue

    # max_chr_len = len(str(max_chr))

    # div_num = float(10**(max_chr_len))

    # for node in g.nodes():
    #     g.node[node]['normpos'] = (g.node[node]['chr'] + g.node[node]['aln_end']/float(chr_length_dict[g.node[node]['chr']]))/div_num

    for edge in g.edges_iter():
        in_node=edge[0]
        out_node=edge[1]