优化颜色集的图像更改

f0ofjuux  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(293)

这是我的代码,用最接近我的颜色集的颜色替换颜色。

def getClosestColor(pixel, color_set_rgb):
    """ Retourne la couleur la plus proche pour le pixel donné """
    closest_color = (75, 82, 99)  # Par défaut noir
    cost_init = 10000
    pixel = np.array(pixel)
    for color in color_set_rgb:
        color = np.array(color)
        cost = np.sum((color - pixel)**2)
        if cost < cost_init:
            cost_init = cost
            closest_color = color
    return closest_color

def getClosestImage(im):  # Get the closest image

    color_set = ['#4B5263', '#B02E26', '#5E7C16', '#3C44AA', '#8932B8', '#F38BAA', '#80C71F', '#FED83D', '#3AB3DA',
                 '#C74EBD', '#F9FFFE']
    color_set_rgb = [ImageColor.getrgb(color) for color in color_set]  # RGB Colorset

    height, width, channels = im.shape
    im_out = np.zeros((height, width, channels))

    for y in range(0, height):
        for x in range(0, width):
            im_out[y, x, :] = getClosestColor(im[y, x], color_set_rgb)

    return im_out

训练时间很长,所以我试着按颜色做:

def getClosestImage(im):  # Get the closest image

    color_set = ['#4B5263', '#B02E26', '#5E7C16', '#3C44AA', '#8932B8', '#F38BAA', '#80C71F', '#FED83D', '#3AB3DA',
                 '#C74EBD', '#F9FFFE']
    color_set_rgb = [ImageColor.getrgb(color) for color in color_set]  # RGB Colorset

    height, width, channels = im.shape
    im_out = np.zeros((height, width, channels))

    for pixel_color in np.unique(im.reshape(-1, 3), axis=0):
        # On récupère les pixels de cette couleur
        mask = np.all(im == pixel_color, axis=2)

        # On rempli avec la nouvelle couleur
        im_out[mask, :] = closest(pixel_color, color_set_rgb)

    return im_out

但这仍然很长。你有什么改进的办法吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题