Python skimage.color.rgb2hsv() Examples

The following are 26 code examples of skimage.color.rgb2hsv(). 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: evaluate.py    From Global_Convolutional_Network with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape[:2]
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) ^ gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    
    img_hsv = color.rgb2hsv(img)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #3
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 #4
Source File: inference.py    From lung-segmentation-2d with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) - gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    img_color = np.dstack((img, img, img))

    img_hsv = color.rgb2hsv(img_color)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #5
Source File: demo.py    From lung-segmentation-2d with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) - gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    img_color = np.dstack((img, img, img))

    img_hsv = color.rgb2hsv(img_color)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #6
Source File: Util.py    From TrackR-CNN with MIT License 6 votes vote down vote up
def get_masked_image(img, mask, multiplier=0.6):
  """
  :param img: The image to be masked.
  :param mask: Binary mask to be applied. The object should be represented by 1 and the background by 0
  :param multiplier: Floating point multiplier that decides the colour of the mask.
  :return: Masked image
  """
  img_mask = np.zeros_like(img)
  indices = np.where(mask == 1)
  img_mask[indices[0], indices[1], 1] = 1
  img_mask_hsv = color.rgb2hsv(img_mask)
  img_hsv = color.rgb2hsv(img)
  img_hsv[indices[0], indices[1], 0] = img_mask_hsv[indices[0], indices[1], 0]
  img_hsv[indices[0], indices[1], 1] = img_mask_hsv[indices[0], indices[1], 1] * multiplier

  return color.hsv2rgb(img_hsv)


# Visualize spatial offset in HSV color space as rotation to spatial center (H),
# distance to spatial center (V) 
Example #7
Source File: Util.py    From PReMVOS with MIT License 6 votes vote down vote up
def get_masked_image(img, mask, multiplier=0.6):
  """
  :param img: The image to be masked.
  :param mask: Binary mask to be applied. The object should be represented by 1 and the background by 0
  :param multiplier: Floating point multiplier that decides the colour of the mask.
  :return: Masked image
  """
  img_mask = np.zeros_like(img)
  indices = np.where(mask == 1)
  img_mask[indices[0], indices[1], 1] = 1
  img_mask_hsv = color.rgb2hsv(img_mask)
  img_hsv = color.rgb2hsv(img)
  img_hsv[indices[0], indices[1], 0] = img_mask_hsv[indices[0], indices[1], 0]
  img_hsv[indices[0], indices[1], 1] = img_mask_hsv[indices[0], indices[1], 1] * multiplier

  return color.hsv2rgb(img_hsv) 
Example #8
Source File: Util.py    From PReMVOS with MIT License 6 votes vote down vote up
def get_masked_image(img, mask, multiplier=0.6):
  """
  :param img: The image to be masked.
  :param mask: Binary mask to be applied. The object should be represented by 1 and the background by 0
  :param multiplier: Floating point multiplier that decides the colour of the mask.
  :return: Masked image
  """
  img_mask = np.zeros_like(img)
  indices = np.where(mask == 1)
  img_mask[indices[0], indices[1], 1] = 1
  img_mask_hsv = color.rgb2hsv(img_mask)
  img_hsv = color.rgb2hsv(img)
  img_hsv[indices[0], indices[1], 0] = img_mask_hsv[indices[0], indices[1], 0]
  img_hsv[indices[0], indices[1], 1] = img_mask_hsv[indices[0], indices[1], 1] * multiplier

  return color.hsv2rgb(img_hsv) 
Example #9
Source File: RDMcolormap.py    From pyrsa with GNU Lesser General Public License v3.0 6 votes vote down vote up
def RDMcolormap(nCols=256):

    # blue-cyan-gray-red-yellow with increasing V (BCGRYincV)
    anchorCols = np.array([
        [0, 0, 1],
        [0, 1, 1],
        [.5, .5, .5],
        [1, 0, 0],
        [1, 1, 0],
    ])

    # skimage rgb2hsv is intended for 3d images (RGB)
    # here we add a new axis to our 2d anchorCols to satisfy skimage, and then squeeze
    anchorCols_hsv = rgb2hsv(anchorCols[np.newaxis, :]).squeeze()

    incVweight = 1
    anchorCols_hsv[:, 2] = (1-incVweight)*anchorCols_hsv[:, 2] + \
        incVweight*np.linspace(0.5, 1, anchorCols.shape[0]).T

    # anchorCols = brightness(anchorCols)
    anchorCols = hsv2rgb(anchorCols_hsv[np.newaxis, :]).squeeze()

    cols = colorScale(nCols, anchorCols)

    return ListedColormap(cols) 
Example #10
Source File: inferences.py    From Global_Convolutional_Network with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape[:2]
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) ^ gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    
    img_hsv = color.rgb2hsv(img)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #11
Source File: ImageTransform.py    From DRFNS with MIT License 6 votes vote down vote up
def _apply_(self, *image):
        res = ()
        n_img = 0
        for img in image:
            if n_img == 0:
                #pdb.set_trace()
                ### transform image into HSV
                img = img_as_ubyte(color.rgb2hsv(img))
                ### perturbe each channel H, E, Dab
                for i in range(3):
                    k_i = self.params['k'][i] 
                    b_i = self.params['b'][i] 
                    img[:,:,i] = GreyValuePerturbation(img[:, :, i], k_i, b_i, MIN=0., MAX=255)
                    #plt.imshow(img[:,:,i], "gray")
                    #plt.show()
                sub_res = img_as_ubyte(color.hsv2rgb(img))
            else:
                sub_res = img

            res += (sub_res,)
            n_img += 1
        return res 
Example #12
Source File: tissue_mask.py    From NCRF with Apache License 2.0 6 votes vote down vote up
def run(args):
    logging.basicConfig(level=logging.INFO)

    slide = openslide.OpenSlide(args.wsi_path)

    # note the shape of img_RGB is the transpose of slide.level_dimensions
    img_RGB = np.transpose(np.array(slide.read_region((0, 0),
                           args.level,
                           slide.level_dimensions[args.level]).convert('RGB')),
                           axes=[1, 0, 2])

    img_HSV = rgb2hsv(img_RGB)

    background_R = img_RGB[:, :, 0] > threshold_otsu(img_RGB[:, :, 0])
    background_G = img_RGB[:, :, 1] > threshold_otsu(img_RGB[:, :, 1])
    background_B = img_RGB[:, :, 2] > threshold_otsu(img_RGB[:, :, 2])
    tissue_RGB = np.logical_not(background_R & background_G & background_B)
    tissue_S = img_HSV[:, :, 1] > threshold_otsu(img_HSV[:, :, 1])
    min_R = img_RGB[:, :, 0] > args.RGB_min
    min_G = img_RGB[:, :, 1] > args.RGB_min
    min_B = img_RGB[:, :, 2] > args.RGB_min

    tissue_mask = tissue_S & tissue_RGB & min_R & min_G & min_B

    np.save(args.npy_path, tissue_mask) 
Example #13
Source File: Util.py    From MOTSFusion with MIT License 6 votes vote down vote up
def get_masked_image(img, mask, multiplier=0.6):
  """
  :param img: The image to be masked.
  :param mask: Binary mask to be applied. The object should be represented by 1 and the background by 0
  :param multiplier: Floating point multiplier that decides the colour of the mask.
  :return: Masked image
  """
  img_mask = np.zeros_like(img)
  indices = np.where(mask == 1)
  img_mask[indices[0], indices[1], 1] = 1
  img_mask_hsv = color.rgb2hsv(img_mask)
  img_hsv = color.rgb2hsv(img)
  img_hsv[indices[0], indices[1], 0] = img_mask_hsv[indices[0], indices[1], 0]
  img_hsv[indices[0], indices[1], 1] = img_mask_hsv[indices[0], indices[1], 1] * multiplier

  return color.hsv2rgb(img_hsv) 
Example #14
Source File: transform.py    From fast-neural-style-keras with Apache License 2.0 5 votes vote down vote up
def original_colors(original, stylized,original_color):
    # Histogram normalization in v channel
    ratio=1. - original_color 

    hsv = color.rgb2hsv(original/255)
    hsv_s = color.rgb2hsv(stylized/255)

    hsv_s[:,:,2] = (ratio* hsv_s[:,:,2]) + (1-ratio)*hsv [:,:,2]
    img = color.hsv2rgb(hsv_s)    
    return img 
Example #15
Source File: utils_visualise.py    From DeepVis-PredDiff with MIT License 5 votes vote down vote up
def get_overlayed_image(x, c, gray_factor_bg = 0.3):    
    '''
    For an image x and a relevance vector c, overlay the image with the 
    relevance vector to visualise the influence of the image pixels.
    '''
    imDim = x.shape[0]
    
    if np.ndim(c)==1:
        c = c.reshape((imDim,imDim))
    if np.ndim(x)==2: # this happens with the MNIST Data
        x = 1-np.dstack((x, x, x))*gray_factor_bg # make it a bit grayish
    if np.ndim(x)==3: # this is what happens with cifar data        
        x = color.rgb2gray(x)
        x = 1-(1-x)*0.5
        x = np.dstack((x,x,x))
        
    alpha = 0.8
    
    # Construct a colour image to superimpose
    im = plt.imshow(c, cmap = cm.seismic, vmin=-np.max(np.abs(c)), vmax=np.max(np.abs(c)), interpolation='nearest')
    color_mask = im.to_rgba(c)[:,:,[0,1,2]]
    
    # Convert the input image and color mask to Hue Saturation Value (HSV) colorspace
    img_hsv = color.rgb2hsv(x)
    color_mask_hsv = color.rgb2hsv(color_mask)
    
    # Replace the hue and saturation of the original image
    # with that of the color mask
    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha
    
    img_masked = color.hsv2rgb(img_hsv)
    
    return img_masked 
Example #16
Source File: caffe_traininglayers.py    From interactive-deep-colorization with MIT License 5 votes vote down vote up
def forward(self, bottom, top):
        for nn in range(self.N):
            top[0].data[nn, :, :, :] = color.rgb2hsv(bottom[0].data[nn, ::-1, :, :].astype('uint8').transpose((1, 2, 0))).transpose((2, 0, 1)) 
Example #17
Source File: image_tfs.py    From tanda with MIT License 5 votes vote down vote up
def TF_shift_hue(x, shift=0.0):
    assert len(x.shape) == 3
    h, w, nc = x.shape

    hsv = rgb2hsv(x)
    hsv[:,:,0] += shift
    return hsv2rgb(hsv) 
Example #18
Source File: __init__.py    From anna with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def color_augment_image(data):
    image = data.transpose(1, 2, 0)
    hsv = color.rgb2hsv(image)

    # Contrast 2
    s_factor1 = numpy.random.uniform(0.25, 4)
    s_factor2 = numpy.random.uniform(0.7, 1.4)
    s_factor3 = numpy.random.uniform(-0.1, 0.1)

    hsv[:, :, 1] = (hsv[:, :, 1] ** s_factor1) * s_factor2 + s_factor3

    v_factor1 = numpy.random.uniform(0.25, 4)
    v_factor2 = numpy.random.uniform(0.7, 1.4)
    v_factor3 = numpy.random.uniform(-0.1, 0.1)

    hsv[:, :, 2] = (hsv[:, :, 2] ** v_factor1) * v_factor2 + v_factor3

    # Color
    h_factor = numpy.random.uniform(-0.1, 0.1)
    hsv[:, :, 0] = hsv[:, :, 0] + h_factor

    hsv[hsv < 0] = 0.0
    hsv[hsv > 1] = 1.0

    rgb = color.hsv2rgb(hsv)

    data_out = rgb.transpose(2, 0, 1)
    return data_out 
Example #19
Source File: make_cifar_p.py    From robustness with Apache License 2.0 5 votes vote down vote up
def brightness(_x, c=0.):
    _x = np.array(_x, copy=True) / 255.
    _x = skcolor.rgb2hsv(_x)
    _x[:, :, 2] = np.clip(_x[:, :, 2] + c, 0, 1)
    _x = skcolor.hsv2rgb(_x)

    return np.uint8(_x * 255) 
Example #20
Source File: make_imagenet_p.py    From robustness with Apache License 2.0 5 votes vote down vote up
def brightness(_x, c=0.):
    _x = np.array(_x, copy=True) / 255.
    _x = skcolor.rgb2hsv(_x)
    _x[:, :, 2] = np.clip(_x[:, :, 2] + c, 0, 1)
    _x = skcolor.hsv2rgb(_x)

    return np.uint8(_x * 255) 
Example #21
Source File: pf6_quadtree_decomposition.py    From aim with MIT License 5 votes vote down vote up
def color_entropy(inp):
    inp = inp / 255.
    img = color.rgb2hsv(inp)
    h_bins = 30
    s_bins = 32
    H = []
    S = []
    img = img.reshape(-1, 3)
    img = [tuple(l) for l in img]
    for pixel in img:
        H.append(pixel[0] * 360.)
        S.append(pixel[1] * 100.)

    h, x = np.histogram(H, bins=h_bins, range=(0, 360), density=True)
    s, y = np.histogram(S, bins=s_bins, range=(0, 100), density=True)

    h = h.ravel()
    h = h * 100.
    h = h + 0.000000000001
    h_log = [math.log(y) for y in h]
    h_result = h * h_log

    s = s.ravel()
    s = s * 100.
    s = s + 0.000000000001
    s_log = [math.log(y) for y in s]
    s_result = s * s_log
    result = abs(np.sum(h_result) + np.sum(s_result)) / 2

    return result


# Recursion 
Example #22
Source File: cp3_HSV_avg.py    From aim with MIT License 5 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)
    img = img / 255. # this division is needed to get proper values. for hue, saturation and value (0 to 360, 0 to 1,0 to 1)
    img = color.rgb2hsv(img)
    img = img.reshape(-1, 3)
    img = [tuple(l) for l in img]

    h = []
    s = []
    v = []

    # Give each channel its own list
    for items in img:
        [hue, sat, val] = [items[0], items[1], items[2]]
        h.append(hue * 360)
        s.append(sat)
        v.append(val)

    # Hue is an angle, so cannot simple add and average it
    sumsin = sum(sind(h[:]))
    sumcos = sum(cosd(h[:]))

    # Get the average value and standard deviation over H,S and V
    avgHue = atan2d(sumsin, sumcos) % 360
    avgSaturation = np.mean(s)
    stdSaturation = np.std(s)
    avgValue = np.mean(v)
    stdValue = np.std(v)
    result = [avgHue, avgSaturation, stdSaturation, avgValue, stdValue]

    return result


# Functions for easy use of radials in sin,cos and tan. based on:
# https://stackoverflow.com/questions/43100286/python-trigonometric-calculations-in-degrees 
Example #23
Source File: make_imagenet_p_inception.py    From robustness with Apache License 2.0 5 votes vote down vote up
def brightness(_x, c=0.):
    _x = np.array(_x, copy=True) / 255.
    _x = skcolor.rgb2hsv(_x)
    _x[:, :, 2] = np.clip(_x[:, :, 2] + c, 0, 1)
    _x = skcolor.hsv2rgb(_x)

    return np.uint8(_x * 255) 
Example #24
Source File: make_imagenet_64_p.py    From robustness with Apache License 2.0 5 votes vote down vote up
def brightness(_x, c=0.):
    _x = np.array(_x, copy=True) / 255.
    _x = skcolor.rgb2hsv(_x)
    _x[:, :, 2] = np.clip(_x[:, :, 2] + c, 0, 1)
    _x = skcolor.hsv2rgb(_x)

    return np.uint8(_x * 255) 
Example #25
Source File: make_tinyimagenet_p.py    From robustness with Apache License 2.0 5 votes vote down vote up
def brightness(_x, c=0.):
    _x = np.array(_x, copy=True) / 255.
    _x = skcolor.rgb2hsv(_x)
    _x[:, :, 2] = np.clip(_x[:, :, 2] + c, 0, 1)
    _x = skcolor.hsv2rgb(_x)

    return np.uint8(_x * 255) 
Example #26
Source File: cp4_HSV_unique.py    From aim with MIT License 4 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)
    img = color.rgb2hsv(img)
    img = img.reshape(-1, 3)
    img = [tuple(l) for l in img]

    hist = collections.Counter(img)
    hist = hist.items()

    hsv_unique = []
    count = []
    h = []
    s = []
    v = []

    for x in range(len(hist)):
        add = [hist[x][0][0], hist[x][0][1], hist[x][0][2]]
        hsv_unique.append(add)
        count.append(hist[x][1])
        h.append(hist[x][0][0])
        s.append(hist[x][0][1])
        v.append(hist[x][0][2])

    # Get all unique values, still has all counts (so no minimal occurence). This probably needs some changing in the future
    h_unique = np.unique(h)
    s_unique = np.unique(s)
    v_unique = np.unique(v)

    new_hsv = []

    # Only often enough occuring values for hsv
    for x in range(len(hsv_unique)):
        if count[x] > 5:
            new_hsv.append(hsv_unique[x])


    result = [len(new_hsv), len(h_unique), len(s_unique), len(v_unique)]

    return result