Python skimage.color.rgb2lab() Examples

The following are 30 code examples of skimage.color.rgb2lab(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module skimage.color , or try the search function .
Example #1
Source File: BatchDatsetReader.py    From Colorization.tensorflow with MIT License 7 votes vote down vote up
def _transform(self, filename):
        try:
            image = misc.imread(filename)
            if len(image.shape) < 3:  # make sure images are of shape(h,w,3)
                image = np.array([image for i in range(3)])

            if self.image_options.get("resize", False) and self.image_options["resize"]:
                resize_size = int(self.image_options["resize_size"])
                resize_image = misc.imresize(image,
                                             [resize_size, resize_size])
            else:
                resize_image = image

            if self.image_options.get("color", False):
                option = self.image_options['color']
                if option == "LAB":
                    resize_image = color.rgb2lab(resize_image)
                elif option == "HSV":
                    resize_image = color.rgb2hsv(resize_image)
        except:
            print ("Error reading file: %s of shape %s" % (filename, str(image.shape)))
            raise

        return np.array(resize_image) 
Example #2
Source File: megafacade.py    From facade-segmentation with MIT License 6 votes vote down vote up
def ransac_guess_color(colors, n_iter=50, std=2):
    colors = rgb2lab(colors)
    colors = colors.reshape(-1, 3)
    masked = colors[:, 0] < 0.1
    colors = colors[~masked]
    assert len(colors) > 0, "Must have at least one color"

    best_mu = np.array([0, 0, 0])
    best_n = 0
    for k in range(n_iter):
        subset = colors[np.random.choice(np.arange(len(colors)), 1)]

        mu = subset.mean(0)
        #inliers = (((colors - mu) ** 2 / std) < 1).all(1)
        inliers = ((np.sqrt(np.sum((colors - mu)**2, axis=1))  / std) < 1)

        mu = colors[inliers].mean(0)
        n = len(colors[inliers])
        if n > best_n:
            best_n = n
            best_mu = mu
    #import ipdb; ipdb.set_trace()
    best_mu = np.squeeze(lab2rgb(np.array([[best_mu]])))
    return best_mu 
Example #3
Source File: __init__.py    From PerceptualSimilarity with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def tensorlab2tensor(lab_tensor,return_inbnd=False):
    from skimage import color
    import warnings
    warnings.filterwarnings("ignore")

    lab = tensor2np(lab_tensor)*100.
    lab[:,:,0] = lab[:,:,0]+50

    rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1)
    if(return_inbnd):
        # convert back to lab, see if we match
        lab_back = color.rgb2lab(rgb_back.astype('uint8'))
        mask = 1.*np.isclose(lab_back,lab,atol=2.)
        mask = np2tensor(np.prod(mask,axis=2)[:,:,np.newaxis])
        return (im2tensor(rgb_back),mask)
    else:
        return im2tensor(rgb_back) 
Example #4
Source File: util.py    From TecoGAN with Apache License 2.0 6 votes vote down vote up
def tensorlab2tensor(lab_tensor,return_inbnd=False):
    from skimage import color
    import warnings
    warnings.filterwarnings("ignore")

    lab = tensor2np(lab_tensor)*100.
    lab[:,:,0] = lab[:,:,0]+50
    # print('lab',lab)

    rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1)
    # print('rgb',rgb_back)
    if(return_inbnd):
        # convert back to lab, see if we match
        lab_back = color.rgb2lab(rgb_back.astype('uint8'))
        # print('lab_back',lab_back)
        # print('lab==lab_back',np.isclose(lab_back,lab,atol=1.))
        # print('lab-lab_back',np.abs(lab-lab_back))
        mask = 1.*np.isclose(lab_back,lab,atol=2.)
        mask = np2tensor(np.prod(mask,axis=2)[:,:,np.newaxis])
        return (im2tensor(rgb_back),mask)
    else:
        return im2tensor(rgb_back) 
Example #5
Source File: panel_pipeline.py    From Comicolorization with MIT License 6 votes vote down vote up
def _draw_process(self, small_input_image, big_input_image):
        lab = rgb2lab(numpy.array(small_input_image))
        lab[:, :, 0] /= 100
        small_image = self.drawer.draw(
            input_images_array=lab.astype(numpy.float32).transpose(2, 0, 1)[numpy.newaxis],
            rgb_images_array=numpy.array(self.reference_image, dtype=numpy.float32).transpose(2, 0, 1)[numpy.newaxis],
        )[0]

        small_image = small_image.convert('RGB')

        if self.drawer_sr is not None:
            drawn_panel_image = self._superresolution_process(small_image, big_input_image)
        else:
            drawn_panel_image = small_image

        return drawn_panel_image 
Example #6
Source File: apply_makeup.py    From visage with MIT License 6 votes vote down vote up
def __add_color(self, intensity):
        """ Adds base colour to all points on lips, at mentioned intensity. """
        val = color.rgb2lab(
            (self.image[self.lip_y, self.lip_x] / 255.)
            .reshape(len(self.lip_y), 1, 3)
        ).reshape(len(self.lip_y), 3)
        l_val, a_val, b_val = np.mean(val[:, 0]), np.mean(val[:, 1]), np.mean(val[:, 2])
        l1_val, a1_val, b1_val = color.rgb2lab(
            np.array(
                (self.red_l / 255., self.green_l / 255., self.blue_l / 255.)
                ).reshape(1, 1, 3)
            ).reshape(3,)
        l_final, a_final, b_final = (l1_val - l_val) * \
            intensity, (a1_val - a_val) * \
            intensity, (b1_val - b_val) * intensity
        val[:, 0] = np.clip(val[:, 0] + l_final, 0, 100)
        val[:, 1] = np.clip(val[:, 1] + a_final, -127, 128)
        val[:, 2] = np.clip(val[:, 2] + b_final, -127, 128)
        self.image[self.lip_y, self.lip_x] = color.lab2rgb(val.reshape(
            len(self.lip_y), 1, 3)).reshape(len(self.lip_y), 3) * 255 
Example #7
Source File: nail.py    From Virtual-Makeup with Apache License 2.0 6 votes vote down vote up
def applyTexture(x, y, texture = texture_input):
	text = imread(texture_input)
	height,width = text.shape[:2]
	xmin, ymin = amin(x),amin(y)
	xmax, ymax = amax(x),amax(y)
	scale = max(((xmax - xmin + 2)/height),((ymax - ymin + 2)/width))
	text = imresize(text, scale)
	# print text.shape[:2]
	# print xmax - xmin +2, ymax - ymin+2
	X = (x-xmin).astype(int)
	Y = (y-ymin).astype(int)
	val1 = color.rgb2lab((text[X, Y]/255.).reshape(len(X), 1, 3)).reshape(len(X), 3)
	val2 = color.rgb2lab((im[x, y]/255.).reshape(len(x), 1, 3)).reshape(len(x), 3)
	L, A, B = mean(val2[:,0]), mean(val2[:,1]), mean(val2[:,2])
	val2[:, 0] = np.clip(val2[:, 0] - L + val1[:,0], 0, 100)
	val2[:, 1] = np.clip(val2[:, 1] - A + val1[:,1], -127, 128)
	val2[:, 2] = np.clip(val2[:, 2] - B + val1[:,2], -127, 128)
	im[x,y] = color.lab2rgb(val2.reshape(len(x), 1, 3)).reshape(len(x), 3)*255

# points = np.loadtxt('nailpoint_5') 
Example #8
Source File: util.py    From SMIT with MIT License 6 votes vote down vote up
def tensorlab2tensor(lab_tensor, return_inbnd=False):
    from skimage import color
    import warnings
    warnings.filterwarnings("ignore")

    lab = tensor2np(lab_tensor) * 100.
    lab[:, :, 0] = lab[:, :, 0] + 50
    # print('lab',lab)

    rgb_back = 255. * np.clip(color.lab2rgb(lab.astype('float')), 0, 1)
    # print('rgb',rgb_back)
    if (return_inbnd):
        # convert back to lab, see if we match
        lab_back = color.rgb2lab(rgb_back.astype('uint8'))
        # print('lab_back',lab_back)
        # print('lab==lab_back',np.isclose(lab_back,lab,atol=1.))
        # print('lab-lab_back',np.abs(lab-lab_back))
        mask = 1. * np.isclose(lab_back, lab, atol=2.)
        mask = np2tensor(np.prod(mask, axis=2)[:, :, np.newaxis])
        return (im2tensor(rgb_back), mask)
    else:
        return im2tensor(rgb_back) 
Example #9
Source File: colorize.py    From reddit_crawlers with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def loadDNN(useGpu = False):
    global net,W_in,H_in,H_out,W_out,lm_lab_l_rs
    if useGpu:    
        gpu_id = 0
        caffe.set_mode_gpu()
        caffe.set_device(gpu_id)
    net = caffe.Net('colorization_deploy_v0.prototxt', 'colorization_release_v0.caffemodel', caffe.TEST)
    print '\n done loading network! \n'

    (H_in,W_in) = net.blobs['data_l'].data.shape[2:] # get input shape
    (H_out,W_out) = net.blobs['class8_ab'].data.shape[2:] # get output shape
    net.blobs['Trecip'].data[...] = 6/np.log(10) # 1/T, set annealing temperature
    
    l_mean = sio.loadmat('ilsvrc_2012_mean.mat')
    lm = np.array(l_mean['mean_data'])
    lm = lm/np.max(lm)
    lm_lab = color.rgb2lab(lm)
    lm_lab_l = lm_lab[:,:,0]
    lm_lab_l = lm_lab_l - np.mean(np.mean(lm_lab_l)) + 50
    lm_lab_l =  Image.fromarray(lm_lab_l)    
    lm_lab_l_rs = lm_lab_l.resize((W_in,H_in), Image.ANTIALIAS) 
Example #10
Source File: util.py    From Text2Colors with MIT License 6 votes vote down vote up
def process_image(image_data, batch_size, imsize):
    input = torch.zeros(batch_size, 1, imsize, imsize)
    labels = torch.zeros(batch_size, 2, imsize, imsize)
    images_np = image_data.numpy().transpose((0, 2, 3, 1))

    for k in range(batch_size):
        img_lab = rgb2lab(images_np[k], illuminant='D50')
        img_l = img_lab[:, :, 0] / 100
        input[k] = torch.from_numpy(np.expand_dims(img_l, 0))

        img_a_scale = (img_lab[:, :, 1:2] + 88) / 185
        img_b_scale = (img_lab[:, :, 2:3] + 127) / 212

        img_ab_scale = np.concatenate((img_a_scale, img_b_scale), axis=2)
        labels[k] = torch.from_numpy(img_ab_scale.transpose((2, 0, 1)))
    return input, labels 
Example #11
Source File: pf6_quadtree_decomposition.py    From aim with MIT License 6 votes vote down vote up
def intensity_entropy(inp):
    img = color.rgb2lab(inp)
    l_bins = 20
    L = []
    img = img.reshape(-1, 3)
    img = [tuple(l) for l in img]
    for pixel in img:
        L.append(pixel[0])

    p, x = np.histogram(L, bins=l_bins, range=(0, 100), normed=True)
    p.ravel()
    p = p * 100.
    p = p + 0.000000000001
    p_log = [math.log(y) for y in p]
    p_result = p * p_log
    result = np.sum(p_result)

    return result


# The uncertainty of colour in a leaf, given the leaf. Based on the shannon entropy 
Example #12
Source File: lab_gamut.py    From interactive-deep-colorization with MIT License 6 votes vote down vote up
def snap_ab(input_l, input_rgb, return_type='rgb'):
    ''' given an input lightness and rgb, snap the color into a region where l,a,b is in-gamut
    '''
    T = 20
    warnings.filterwarnings("ignore")
    input_lab = rgb2lab_1d(np.array(input_rgb))  # convert input to lab
    conv_lab = input_lab.copy()  # keep ab from input
    for t in range(T):
        conv_lab[0] = input_l  # overwrite input l with input ab
        old_lab = conv_lab
        tmp_rgb = color.lab2rgb(conv_lab[np.newaxis, np.newaxis, :]).flatten()
        tmp_rgb = np.clip(tmp_rgb, 0, 1)
        conv_lab = color.rgb2lab(tmp_rgb[np.newaxis, np.newaxis, :]).flatten()
        dif_lab = np.sum(np.abs(conv_lab - old_lab))
        if dif_lab < 1:
            break
        # print(conv_lab)

    conv_rgb_ingamut = lab2rgb_1d(conv_lab, clip=True, dtype='uint8')
    if (return_type == 'rgb'):
        return conv_rgb_ingamut

    elif(return_type == 'lab'):
        conv_lab_ingamut = rgb2lab_1d(conv_rgb_ingamut)
        return conv_lab_ingamut 
Example #13
Source File: dataloader.py    From Tag2Pix with MIT License 6 votes vote down vote up
def __call__(self, img):
        if self.color_space == 'rgb':
            return (img * 2 - 1.)

        img = img.permute(1, 2, 0) # to [H, W, 3]
        if self.color_space == 'lab':
            img = color.rgb2lab(img) # [0~100, -128~127, -128~127]
            img[:,:,0] = (img[:,:,0] - 50.0) * (1 / 50.)
            img[:,:,1] = (img[:,:,1] + 0.5) * (1 / 127.5)
            img[:,:,2] = (img[:,:,2] + 0.5) * (1 / 127.5)
        elif self.color_space == 'hsv':
            img = color.rgb2hsv(img) # [0~1, 0~1, 0~1]
            img = (img * 2 - 1)

        # to [3, H, W]
        return torch.from_numpy(img).float().permute(2, 0, 1) # [-1~1, -1~1, -1~1] 
Example #14
Source File: cp5_LAB_avg.py    From aim with MIT License 6 votes vote down vote up
def execute(b64):
    b64 = base64.b64decode(b64)
    b64 = BytesIO(b64)
    img = Image.open(b64)
    img= np.array(img)
    img = util.img_as_ubyte(img)

    # Convert the LAB space
    lab = color.rgb2lab(img)

    L = lab[:, :, 0]
    A = lab[:, :, 1]
    B = lab[:, :, 2]

    # Get average and standard deviation for each value separately
    meanL = np.mean(L)
    stdL = np.std(L)
    meanA = np.mean(A)
    stdA = np.std(A)
    meanB = np.mean(B)
    stdB = np.std(B)

    result = [meanL, stdL, meanA, stdA, meanB, stdB]

    return result 
Example #15
Source File: make_dataset.py    From DeepLearningImplementations with MIT License 6 votes vote down vote up
def format_image(img_path, size):
    """
    Load img with opencv and reshape
    """

    img_color = cv2.imread(img_path)
    img_color = img_color[:, :, ::-1]
    img_black = cv2.imread(img_path, 0)

    img_color = cv2.resize(img_color, (size, size), interpolation=cv2.INTER_AREA)
    img_black = cv2.resize(img_black, (size, size), interpolation=cv2.INTER_AREA)

    img_lab = color.rgb2lab(img_color)

    img_lab = img_lab.reshape((1, size, size, 3)).transpose(0, 3, 1, 2)
    img_color = img_color.reshape((1, size, size, 3)).transpose(0, 3, 1, 2)
    img_black = img_black.reshape((1, size, size, 1)).transpose(0, 3, 1, 2)

    return img_color, img_lab, img_black 
Example #16
Source File: lab_image_record.py    From deep-koalarization with MIT License 6 votes vote down vote up
def write_image(self, img_file, image, img_embedding):
        img = transform.resize(image, img_shape, mode="constant")
        lab = color.rgb2lab(img).astype(np.float32)
        l_channel = 2 * lab[:, :, 0] / 100 - 1
        ab_channels = lab[:, :, 1:] / 127
        example = tf.train.Example(
            features=tf.train.Features(
                feature={
                    "image_name": self._bytes_feature(img_file),
                    "image_l": self._float32_list(l_channel.flatten()),
                    "image_ab": self._float32_list(ab_channels.flatten()),
                    "image_embedding": self._float32_list(img_embedding.flatten()),
                }
            )
        )
        self.write(example.SerializeToString()) 
Example #17
Source File: nlc.py    From videoseg with MIT License 5 votes vote down vote up
def color_hist(im, colBins):
    """
    Get color histogram descriptors for RGB and LAB space.
    Input: im: (h,w,c): 0-255: np.uint8: RGB
    Output: descriptor: (colBins*6,)
    """
    assert im.ndim == 3 and im.shape[2] == 3, "image should be rgb"
    arr = np.concatenate((im, color.rgb2lab(im)), axis=2).reshape((-1, 6))
    desc = np.zeros((colBins * 6,), dtype=np.float)
    for i in range(3):
        desc[i * colBins:(i + 1) * colBins], _ = np.histogram(
            arr[:, i], bins=colBins, range=(0, 255))
        desc[i * colBins:(i + 1) * colBins] /= np.sum(
            desc[i * colBins:(i + 1) * colBins]) + (
            np.sum(desc[i * colBins:(i + 1) * colBins]) < 1e-4)
    i += 1
    desc[i * colBins:(i + 1) * colBins], _ = np.histogram(
        arr[:, i], bins=colBins, range=(0, 100))
    desc[i * colBins:(i + 1) * colBins] /= np.sum(
        desc[i * colBins:(i + 1) * colBins]) + (
        np.sum(desc[i * colBins:(i + 1) * colBins]) < 1e-4)
    for i in range(4, 6):
        desc[i * colBins:(i + 1) * colBins], _ = np.histogram(
            arr[:, i], bins=colBins, range=(-128, 127))
        desc[i * colBins:(i + 1) * colBins] /= np.sum(
            desc[i * colBins:(i + 1) * colBins]) + (
            np.sum(desc[i * colBins:(i + 1) * colBins]) < 1e-4)
    return desc 
Example #18
Source File: test_colorization.py    From deep-koalarization with MIT License 5 votes vote down vote up
def _tensors(self):
        """
        Create the input and target tensors to feed the network.
        Even if the actual sample is just one, it is batched in a batch of 10
        :return:
        """
        # Image sizes
        width = 128
        height = 64

        # The target image is a simple checkboard pattern
        img = np.zeros((width, height, 3), dtype=np.uint8)
        img[: width // 2, :, 0] = 255
        img[:, height // 2 :, 1] = 255
        img[: width // 2, : height // 2, 2] = 255

        # Simulate a batch of Lab images with size [width, height]
        # and Lab values in the range [-1, 1]
        lab = color.rgb2lab(img).astype(np.float32)
        l, ab = lab[:, :, 0], lab[:, :, 1:]
        l = 2 * l / 100 - 1
        l = l.reshape([width, height, 1])
        ab /= 127

        imgs_l, imgs_ab, imgs_emb = tf.train.batch(
            [
                tf.convert_to_tensor(l),
                tf.convert_to_tensor(ab),
                tf.truncated_normal(shape=[1001]),
            ],
            batch_size=10,
        )
        return imgs_l, imgs_ab, imgs_emb 
Example #19
Source File: input.py    From intrinsic with MIT License 5 votes vote down vote up
def image_lab(self):
        """ Image in L*a*b* space """
        if not hasattr(self, '_image_lab'):
            self._image_lab = rgb2lab(self._image_rgb)
            self._image_lab.setflags(write=False)
        return self._image_lab 
Example #20
Source File: util.py    From SMIT with MIT License 5 votes vote down vote up
def rgb2lab(input):
    from skimage import color
    return color.rgb2lab(input / 255.) 
Example #21
Source File: colorize.py    From reddit_crawlers with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def runDNN(imagePath):
    global net,W_in,H_in,H_out,W_out
    if net is None:
        print 'Fuck you!'
        return -1
    # load the original image
    img_rgb = caffe.io.load_image(imagePath)
    (H_orig,W_orig) = img_rgb.shape[:2] # original image size
    img_lab = color.rgb2lab(img_rgb) # convert image to lab color space
    img_l = img_lab[:,:,0] # pull out L channel

    # Strech the histogram
    powerFactor = 1
    img_l = img_l - np.min(img_l)
    img_l = img_l / np.max(img_l) * 2
    img_l = np.power(img_l,powerFactor) * 100/np.power(2,powerFactor)
    
    # resize image to network input size
    img_rs = caffe.io.resize_image(img_rgb,(H_in,W_in)) # resize image to network input size
    img_lab_rs = color.rgb2lab(img_rs)
    img_l_rs = img_lab_rs[:,:,0]

    # Strech the histogram
    img_l_rs = img_l_rs - np.min(img_l_rs)
    img_l_rs = img_l_rs / np.max(img_l_rs) * 2
    img_l_rs = np.power(img_l_rs,powerFactor) * 100/np.power(2,powerFactor)    
    
    net.blobs['data_l'].data[0,0,:,:] = img_l_rs - lm_lab_l_rs # subtract 50 for mean-centering
    net.forward() # run network
    print '\n finish going through network! \n'
    
    ab_dec = net.blobs['class8_ab'].data[0,:,:,:].transpose((1,2,0)) # this is our result
    ab_dec_us = sni.zoom(ab_dec,(1.*H_orig/H_out,1.*W_orig/W_out,1)) # upsample to match size of original image L
    img_lab_out = np.concatenate((img_l[:,:,np.newaxis],ab_dec_us),axis=2) # concatenate with original image L
    img_rgb_out = np.clip(color.lab2rgb(img_lab_out),0,1) # convert back to rgb
    return (img_rgb_out[:,:,[2,1,0]]*255.0).astype('uint8') 
Example #22
Source File: data_loader.py    From Text2Colors with MIT License 5 votes vote down vote up
def __init__(self, input_dict, txt_path, pal_path, img_path, transform=None):
        self.transform = transform
        with open(img_path, 'rb') as f:
            self.images = np.asarray(pickle.load(f)) / 255
        with open(txt_path, 'rb') as fin:
            self.src_seqs = pickle.load(fin)
        with open(pal_path, 'rb') as fin:
            self.trg_seqs = pickle.load(fin)

        # ==================== Preprocessing src_seqs ====================#
        # Return a list of indexes, one for each word in the sentence.
        words_index = []
        for index, palette_name in enumerate(self.src_seqs):
            # Set list size to the longest palette name.
            temp = [0] * input_dict.max_len
            for i, word in enumerate(palette_name):
                temp[i] = input_dict.word2index[word]
            words_index.append(temp)

        self.src_seqs = torch.LongTensor(words_index)

        # ==================== Preprocessing trg_seqs ====================#
        palette_list = []
        for palettes in self.trg_seqs:
            temp = []
            for palette in palettes:
                rgb = np.array([palette[0], palette[1], palette[2]]) / 255.0
                warnings.filterwarnings("ignore")
                lab = rgb2lab(rgb[np.newaxis, np.newaxis, :], illuminant='D50').flatten()
                temp.append(lab[0])
                temp.append(lab[1])
                temp.append(lab[2])
            palette_list.append(temp)

        self.trg_seqs = torch.FloatTensor(palette_list)

        self.num_total_data = len(self.src_seqs) 
Example #23
Source File: util.py    From SMIT with MIT License 5 votes vote down vote up
def tensor2tensorlab(image_tensor, to_norm=True, mc_only=False):
    # image tensor to lab tensor
    from skimage import color

    img = tensor2im(image_tensor)
    # print('img_rgb',img.flatten())
    img_lab = color.rgb2lab(img)
    # print('img_lab',img_lab.flatten())
    if (mc_only):
        img_lab[:, :, 0] = img_lab[:, :, 0] - 50
    if (to_norm and not mc_only):
        img_lab[:, :, 0] = img_lab[:, :, 0] - 50
        img_lab = img_lab / 100.

    return np2tensor(img_lab) 
Example #24
Source File: util.py    From SMIT with MIT License 5 votes vote down vote up
def dssim(p0, p1, range=255.):
    return (1 - compare_ssim(p0, p1, data_range=range, multichannel=True)) / 2.


# def rgb2lab(in_img, mean_cent=False):
#     from skimage import color
#     img_lab = color.rgb2lab(in_img)
#     if (mean_cent):
#         img_lab[:, :, 0] = img_lab[:, :, 0] - 50
#     return img_lab 
Example #25
Source File: util.py    From TecoGAN with Apache License 2.0 5 votes vote down vote up
def rgb2lab(input):
    from skimage import color
    return color.rgb2lab(input / 255.) 
Example #26
Source File: data_loader.py    From Text2Colors with MIT License 5 votes vote down vote up
def __init__(self, src_path, trg_path, input_dict):
        with open(src_path, 'rb') as fin:
            self.src_seqs = pickle.load(fin)
        with open(trg_path, 'rb') as fin:
            self.trg_seqs = pickle.load(fin)

        words_index = []
        for index, palette_name in enumerate(self.src_seqs):
            temp = [0] * input_dict.max_len

            for i, word in enumerate(palette_name):
                temp[i] = input_dict.word2index[word]
            words_index.append(temp)
        self.src_seqs = torch.LongTensor(words_index)

        palette_list = []
        for index, palettes in enumerate(self.trg_seqs):
            temp = []
            for palette in palettes:
                rgb = np.array([palette[0], palette[1], palette[2]]) / 255.0
                warnings.filterwarnings("ignore")
                lab = rgb2lab(rgb[np.newaxis, np.newaxis, :], illuminant='D50').flatten()
                temp.append(lab[0])
                temp.append(lab[1])
                temp.append(lab[2])
            palette_list.append(temp)

        self.trg_seqs = torch.FloatTensor(palette_list)
        self.num_total_seqs = len(self.src_seqs) 
Example #27
Source File: Distance.py    From Zolver with MIT License 5 votes vote down vote up
def real_edge_compute(e1, e2):
    """
        Return the distance between colors of two edges for real puzzle.

        :param e1: Edge object
        :param e2: Edge object
        :return: distance Float
    """
    
    rgbs1 = []
    rgbs2 = []
    if not have_edges_similar_length(e1, e2, 0.20):
        return float('inf')

    e1_lab_colors = []
    for col in e1.color:
        rgb = colorsys.hls_to_rgb(col[0], col[1], col[2])
        rgb = [x * 255.0 for x in rgb]
        rgbs1.append(rgb)
        e1_lab_colors.append(color.rgb2lab([[[rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0]]])[0][0])
        # Drop luminance
        e1_lab_colors[-1] = [0, e1_lab_colors[-1][1], e1_lab_colors[-1][2]]

    e2_lab_colors = []
    for col in e2.color:
        rgb = colorsys.hls_to_rgb(col[0], col[1], col[2])
        rgb = [x * 255.0 for x in rgb]
        rgbs2.append(rgb)
        e2_lab_colors.append(color.rgb2lab([[[rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0]]])[0][0])
        # Drop Luminance
        e2_lab_colors[-1] = [0, e2_lab_colors[-1][1], e2_lab_colors[-1][2]]

    return min(euclideanDistance(e1_lab_colors, e2_lab_colors), euclideanDistance(e1_lab_colors, e2_lab_colors[::-1])) 
Example #28
Source File: util.py    From TecoGAN with Apache License 2.0 5 votes vote down vote up
def tensor2tensorlab(image_tensor,to_norm=True,mc_only=False):
    # image tensor to lab tensor
    from skimage import color

    img = tensor2im(image_tensor)
    # print('img_rgb',img.flatten())
    img_lab = color.rgb2lab(img)
    # print('img_lab',img_lab.flatten())
    if(mc_only):
        img_lab[:,:,0] = img_lab[:,:,0]-50
    if(to_norm and not mc_only):
        img_lab[:,:,0] = img_lab[:,:,0]-50
        img_lab = img_lab/100.

    return np2tensor(img_lab) 
Example #29
Source File: util.py    From TecoGAN with Apache License 2.0 5 votes vote down vote up
def rgb2lab(in_img,mean_cent=False):
    from skimage import color
    img_lab = color.rgb2lab(in_img)
    if(mean_cent):
        img_lab[:,:,0] = img_lab[:,:,0]-50
    return img_lab 
Example #30
Source File: __init__.py    From PerceptualSimilarity with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def rgb2lab(input):
    from skimage import color
    return color.rgb2lab(input / 255.)