Python matplotlib.colors.rgb_to_hsv() Examples

The following are 12 code examples of matplotlib.colors.rgb_to_hsv(). 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 matplotlib.colors , or try the search function .
Example #1
Source File: test_colors.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_rgb_hsv_round_trip():
    for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]:
        np.random.seed(0)
        tt = np.random.random(a_shape)
        assert_array_almost_equal(tt,
            mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt)))
        assert_array_almost_equal(tt,
            mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt))) 
Example #2
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_rgb_hsv_round_trip():
    for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]:
        np.random.seed(0)
        tt = np.random.random(a_shape)
        assert_array_almost_equal(tt,
            mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt)))
        assert_array_almost_equal(tt,
            mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt))) 
Example #3
Source File: test_colors.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_rgb_hsv_round_trip():
    for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]:
        np.random.seed(0)
        tt = np.random.random(a_shape)
        assert_array_almost_equal(tt,
            mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt)))
        assert_array_almost_equal(tt,
            mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt))) 
Example #4
Source File: color.py    From phy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _override_hsv(rgb, h=None, s=None, v=None):
    h_, s_, v_ = rgb_to_hsv(np.array([[rgb]])).flat
    h = h if h is not None else h_
    s = s if s is not None else s_
    v = v if v is not None else v_
    r, g, b = hsv_to_rgb(np.array([[[h, s, v]]])).flat
    return r, g, b


#------------------------------------------------------------------------------
# Colormap utilities
#------------------------------------------------------------------------------ 
Example #5
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_rgb_hsv_round_trip():
    for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]:
        np.random.seed(0)
        tt = np.random.random(a_shape)
        assert_array_almost_equal(tt,
            mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt)))
        assert_array_almost_equal(tt,
            mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt))) 
Example #6
Source File: pedestrianDetection.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def imageColorHist(imgPath,imgList,nrows):
    ncols=math.ceil(len(imgList)/nrows)
    fig,axes=plt.subplots(ncols,nrows,sharex=True,sharey=True,figsize=(15,20))
    ax=axes.flatten()
    #print(ax)
    num_bins = 50  #设置直方图的bin参数,及柱数量
    totalH=np.array([])
    totalS=np.array([])
    totalV=np.array([])
    
    for i in range(len(imgList)):
    #for i in range(3):
        #print(i)
        img=os.path.join(imgPath,imgList[i])
        lum_img=mpimg.imread(img)
        lum_imgSmall=misc.imresize(lum_img, 0.3)
        lum_imgSmallHSV=mpc.rgb_to_hsv(lum_imgSmall/255) #RGB空间结构不符合人们对颜色相似性的主观判断,因此将其转换为HSV空间、更接近于人们对颜色的主观认识。色调(H),饱和度(S),明度(V)
        #print(lum_imgSmallHSV[...,0].reshape(-1))
        ax[i].hist(lum_imgSmallHSV[...,0].reshape(-1), num_bins, normed=1)  #提取H色调分量
        #print(totalH.shape,lum_imgSmallHSV[...,0].reshape(-1).shape)
        totalH=np.append(totalH,lum_imgSmallHSV[...,0].reshape(-1))
        totalS=np.append(totalS,lum_imgSmallHSV[...,1].reshape(-1))
        totalV=np.append(totalV,lum_imgSmallHSV[...,2].reshape(-1))
        ax[i].set_title(i+1)
    fig.tight_layout()
    fig.suptitle("images show",fontsize=14,fontweight='bold',y=1.02)
    
    totalStat,(totalAXH,totalAXS,totalAXV)=plt.subplots(ncols=3,figsize=(20, 6))  #建立新图表,用于显示总体HSV的直方图统计
    totalAXH.hist(totalH*360,num_bins,normed=1,facecolor='y')    
    totalAXS.hist(totalS*100,num_bins,normed=1,facecolor='k')
    totalAXV.hist(totalV*100,num_bins,normed=1,facecolor='g')
   
    plt.show() 
Example #7
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_rgb_hsv_round_trip():
    for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]:
        np.random.seed(0)
        tt = np.random.random(a_shape)
        assert_array_almost_equal(tt,
            mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt)))
        assert_array_almost_equal(tt,
            mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt))) 
Example #8
Source File: test.py    From Semantic-Segmentation with MIT License 4 votes vote down vote up
def get_random_data(image, label, input_shape, jitter=.2, hue=.2, sat=1.1, val=1.1):
    h, w = input_shape

    # resize image
    rand_jit1 = rand(1-jitter,1+jitter)
    rand_jit2 = rand(1-jitter,1+jitter)
    new_ar = w/h * rand_jit1/rand_jit2
    scale = rand(.6, 1.4)
    if new_ar < 1:
        nh = int(scale*h)
        nw = int(nh*new_ar)
    else:
        nw = int(scale*w)
        nh = int(nw/new_ar)
    image = image.resize((nw,nh), Image.BICUBIC)
    label = label.resize((nw,nh), Image.BICUBIC)
    # place image
    dx = int(rand(0, w-nw))
    dy = int(rand(0, h-nh))
    new_image = Image.new('RGB', (w,h), (0,0,0))
    new_label = Image.new('RGB', (w,h), (0,0,0))
    new_image.paste(image, (dx, dy))
    new_label.paste(label, (dx, dy))
    image = new_image
    label = new_label
    # flip image or not
    flip = rand()<.5
    if flip: 
        image = image.transpose(Image.FLIP_LEFT_RIGHT)
        label = label.transpose(Image.FLIP_LEFT_RIGHT)

    # distort image
    hue = rand(-hue, hue)
    sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)
    val = rand(1, val) if rand()<.5 else 1/rand(1, val)
    x = rgb_to_hsv(np.array(image)/255.)
    x[..., 0] += hue
    x[..., 0][x[..., 0]>1] -= 1
    x[..., 0][x[..., 0]<0] += 1
    x[..., 1] *= sat
    x[..., 2] *= val
    x[x>1] = 1
    x[x<0] = 0
    image_data = hsv_to_rgb(x)
    return image_data,label 
Example #9
Source File: train.py    From Semantic-Segmentation with MIT License 4 votes vote down vote up
def get_random_data(image, label, input_shape, jitter=.1, hue=.1, sat=1.1, val=1.1):

    h, w = input_shape

    # resize image
    rand_jit1 = rand(1-jitter,1+jitter)
    rand_jit2 = rand(1-jitter,1+jitter)
    new_ar = w/h * rand_jit1/rand_jit2
    scale = rand(.7, 1.3)
    if new_ar < 1:
        nh = int(scale*h)
        nw = int(nh*new_ar)
    else:
        nw = int(scale*w)
        nh = int(nw/new_ar)
    image = image.resize((nw,nh), Image.NEAREST)
    label = label.resize((nw,nh), Image.NEAREST)
    # place image
    dx = int(rand(0, w-nw))
    dy = int(rand(0, h-nh))
    new_image = Image.new('RGB', (w,h), (0,0,0))
    new_label = Image.new('RGB', (w,h), (0,0,0))
    new_image.paste(image, (dx, dy))
    new_label.paste(label, (dx, dy))
    image = new_image
    label = new_label
    # flip image or not
    flip = rand()<.5
    if flip: 
        image = image.transpose(Image.FLIP_LEFT_RIGHT)
        label = label.transpose(Image.FLIP_LEFT_RIGHT)

    # distort image
    hue = rand(-hue, hue)
    sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)
    val = rand(1, val) if rand()<.5 else 1/rand(1, val)
    x = rgb_to_hsv(np.array(image)/255.)
    x[..., 0] += hue
    x[..., 0][x[..., 0]>1] -= 1
    x[..., 0][x[..., 0]<0] += 1
    x[..., 1] *= sat
    x[..., 2] *= val
    x[x>1] = 1
    x[x<0] = 0
    image_data = hsv_to_rgb(x) 
    return image_data,label 
Example #10
Source File: utils.py    From yolo3-keras with MIT License 4 votes vote down vote up
def get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True):
    '''r实时数据增强的随机预处理'''
    line = annotation_line.split()
    image = Image.open(line[0])
    iw, ih = image.size
    h, w = input_shape
    box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])

    # resize image
    new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter)
    scale = rand(.25, 2)
    if new_ar < 1:
        nh = int(scale*h)
        nw = int(nh*new_ar)
    else:
        nw = int(scale*w)
        nh = int(nw/new_ar)
    image = image.resize((nw,nh), Image.BICUBIC)

    # place image
    dx = int(rand(0, w-nw))
    dy = int(rand(0, h-nh))
    new_image = Image.new('RGB', (w,h), (128,128,128))
    new_image.paste(image, (dx, dy))
    image = new_image

    # flip image or not
    flip = rand()<.5
    if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)

    # distort image
    hue = rand(-hue, hue)
    sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)
    val = rand(1, val) if rand()<.5 else 1/rand(1, val)
    x = rgb_to_hsv(np.array(image)/255.)
    x[..., 0] += hue
    x[..., 0][x[..., 0]>1] -= 1
    x[..., 0][x[..., 0]<0] += 1
    x[..., 1] *= sat
    x[..., 2] *= val
    x[x>1] = 1
    x[x<0] = 0
    image_data = hsv_to_rgb(x) # numpy array, 0 to 1

    # correct boxes
    box_data = np.zeros((max_boxes,5))
    if len(box)>0:
        np.random.shuffle(box)
        box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx
        box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy
        if flip: box[:, [0,2]] = w - box[:, [2,0]]
        box[:, 0:2][box[:, 0:2]<0] = 0
        box[:, 2][box[:, 2]>w] = w
        box[:, 3][box[:, 3]>h] = h
        box_w = box[:, 2] - box[:, 0]
        box_h = box[:, 3] - box[:, 1]
        box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box
        if len(box)>max_boxes: box = box[:max_boxes]
        box_data[:len(box)] = box

    return image_data, box_data 
Example #11
Source File: common.py    From semantic-embeddings with MIT License 4 votes vote down vote up
def distort_color(img, fast_mode=True,
                  brightness_delta=32./255., hue_delta=0.2, saturation_range=(0.5, 1.5), contrast_range=(0.5, 1.5),
                  data_format='channels_last'):
    
    nonnormalized = (img.max() > 2.0)
    if nonnormalized:
        img = img.astype(np.float32) / 255.
    if data_format == 'channels_first':
        img = np.transpose(img, (1, 2, 0))
    if (not nonnormalized) and (data_format == 'channels_last'):
        img = img.copy()

    noop = lambda x: x
    brightness_hsv = (lambda x: random_brightness_hsv(x, max_delta=brightness_delta)) if brightness_delta > 0 else noop
    saturation = (lambda x: random_saturation(x, *saturation_range)) if (saturation_range[0] <= saturation_range[1]) and ((saturation_range[0] != 1) or (saturation_range[1] != 1)) else noop
    
    if fast_mode:

        ordering = np.random.choice(2)
        if ordering == 0:
            img = hsv_to_rgb(saturation(brightness_hsv(rgb_to_hsv(img))))
        else:
            img = hsv_to_rgb(brightness_hsv(saturation(rgb_to_hsv(img))))

    else:

        brightness = (lambda x: random_brightness(x, max_delta=brightness_delta)) if brightness_delta > 0 else noop
        hue = (lambda x: random_hue(x, max_delta=hue_delta)) if hue_delta > 0 else noop
        contrast = (lambda x: random_contrast(x, *contrast_range)) if (contrast_range[0] <= contrast_range[1]) and ((contrast_range[0] != 1) or (contrast_range[1] != 1)) else noop

        ordering = np.random.choice(4)
        if ordering == 0:
            img = contrast(hsv_to_rgb(hue(saturation(rgb_to_hsv(brightness(img))))))
        elif ordering == 1:
            img = hsv_to_rgb(hue(rgb_to_hsv(contrast(brightness(hsv_to_rgb(saturation(rgb_to_hsv(img))))))))
        elif ordering == 2:
            img = hsv_to_rgb(saturation(brightness_hsv(hue(rgb_to_hsv(contrast(img))))))
        elif ordering == 3:
            img = brightness(contrast(hsv_to_rgb(saturation(hue(rgb_to_hsv(img))))))

    if data_format == 'channels_first':
        img = np.transpose(img, (2, 0, 1))
    if nonnormalized:
        img = img * 255.
    
    return img 
Example #12
Source File: named_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_colortable(colors, title, sort_colors=True, emptycols=0):

    cell_width = 212
    cell_height = 22
    swatch_width = 48
    margin = 12
    topmargin = 40

    # Sort colors by hue, saturation, value and name.
    by_hsv = ((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                    for name, color in colors.items())
    if sort_colors is True:
        by_hsv = sorted(by_hsv)
    names = [name for hsv, name in by_hsv]

    n = len(names)
    ncols = 4 - emptycols
    nrows = n // ncols + int(n % ncols > 0)

    width = cell_width * 4 + 2 * margin
    height = cell_height * nrows + margin + topmargin
    dpi = 72

    fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
    fig.subplots_adjust(margin/width, margin/height,
                        (width-margin)/width, (height-topmargin)/height)
    ax.set_xlim(0, cell_width * 4)
    ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
    ax.yaxis.set_visible(False)
    ax.xaxis.set_visible(False)
    ax.set_axis_off()
    ax.set_title(title, fontsize=24, loc="left", pad=10)

    for i, name in enumerate(names):
        row = i % nrows
        col = i // nrows
        y = row * cell_height

        swatch_start_x = cell_width * col
        swatch_end_x = cell_width * col + swatch_width
        text_pos_x = cell_width * col + swatch_width + 7

        ax.text(text_pos_x, y, name, fontsize=14,
                horizontalalignment='left',
                verticalalignment='center')

        ax.hlines(y, swatch_start_x, swatch_end_x,
                  color=colors[name], linewidth=18)

    return fig