当前位置: 首页>>代码示例>>Python>>正文


Python color.rgb2hsv函数代码示例

本文整理汇总了Python中skimage.color.rgb2hsv函数的典型用法代码示例。如果您正苦于以下问题:Python rgb2hsv函数的具体用法?Python rgb2hsv怎么用?Python rgb2hsv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了rgb2hsv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getFeatures

def getFeatures(fn):
    if isinstance(fn,str):
        cropped_pillow_im = crop_border(fn)
        # converting between PIL images and skimage ubyte is easy!
        pic = img_as_ubyte(cropped_pillow_im) # uint8
    else:
        pic = fn
    if pic.shape[1] < 50:
        return None, None # too narrow
    hues = rgb2hsv(pic)[:,:,0]
    brightness = rgb2hsv(pic)[:,:,2] # Value in HSV
    # std, mean, median
    std = np.std(hues)
    diff_avg = abs(np.mean(hues)-np.median(hues))
    hue_vals = get_popular_values(hues, num=2)
    brightness_vals = get_popular_values(brightness, num=3)
    pixel_count = sum(np.histogram(hues)[0])
    first_two_colors_close = (abs(hue_vals[0].idx - hue_vals[1].idx) == 1) or (hue_vals[0].idx==0 and\
        hue_vals[1].idx==hue_vals[1].maxidx ) or (hue_vals[0].idx==hue_vals[0].maxidx and hue_vals[1].idx==0)\
        or (hue_vals[1].cnt <(0.1 * pixel_count))
    good_contrast = True
    if std == 0.0: # no variance in hue means grayscale image
        good_contrast = abs(brightness_vals[0].idx - brightness_vals[1].idx) < 3 
    res = Feature(std, diff_avg,  first_two_colors_close, good_contrast)

    if not isGood(res):
        return None, None

    newy = int(len(pic[0]) / (len(pic) / 250.0))
    pic = resize(pic, (250, newy), mode="nearest")
    return res, pic
开发者ID:carolinux,项目名称:mosaic,代码行数:31,代码来源:average.py

示例2: main

def main():
    # read the images
    image_from = io.imread(name_from) / 256
    image_to = io.imread(name_to) / 256

    # change to hsv domain (if requested)
    if args.use_hsv:
        image_from[:] = rgb2hsv(image_from)
        image_to[:] = rgb2hsv(image_to)

    # get shapes
    shape_from = image_from.shape
    shape_to = image_to.shape

    # flatten
    X_from = im2mat(image_from)
    X_to = im2mat(image_to)

    # number of pixes
    n_pixels_from = X_from.shape[0]
    n_pixels_to = X_to.shape[0]

    # subsample
    X_from_ss = X_from[np.random.randint(0, n_pixels_from-1, n_pixels),:]
    X_to_ss = X_to[np.random.randint(0, n_pixels_to-1, n_pixels),:]

    if save_col_distribution:
        import matplotlib.pyplot as plt
        import seaborn as sns
        sns.set_style('white')

        fig, axes = plt.subplots(nrows=2, figsize=(5, 10))
        for ax, X in zip(axes, [X_from_ss, X_to_ss]):
            ax.scatter(X[:,0], X[:,1], color=X)
            if args.use_hsv:
                ax.set_xhsvel('hue')
                ax.set_yhsvel('value')
            else:
                ax.set_xhsvel('red')
                ax.set_yhsvel('green')
        axes[0].set_title('distr. from')
        axes[1].set_title('distr. to')
        fig.tight_layout()
        fig.savefig('color_distributions.png')

    # optimal tranportation
    ot_color = OptimalTransport(X_to_ss, X_from_ss, lam=lam,
                                    distance_metric=distance_metric)

    # model transfer
    transfer_model = KNeighborsRegressor(n_neighbors=n_neighbors)
    transfer_model.fit(X_to_ss, n_pixels * ot_color.P @ X_from_ss)
    X_transfered = transfer_model.predict(X_to)

    image_transferd = minmax(mat2im(X_transfered, shape_to))
    if args.use_hsv:
        image_transferd[:] = hsv2rgb(image_transferd)
    io.imsave(name_out, image_transferd)
开发者ID:MichielStock,项目名称:Teaching,代码行数:58,代码来源:color_transfer.py

示例3: test_hsv_value_with_non_float_output

def test_hsv_value_with_non_float_output():
    # Since `rgb2hsv` returns a float image and the result of the filtered
    # result is inserted into the HSV image, we want to make sure there isn't
    # a dtype mismatch.
    filtered = edges_hsv_uint(COLOR_IMAGE)
    filtered_value = color.rgb2hsv(filtered)[:, :, 2]
    value = color.rgb2hsv(COLOR_IMAGE)[:, :, 2]
    # Reduce tolerance because dtype conversion.
    assert_allclose(filtered_value, filters.sobel(value), rtol=1e-5, atol=1e-5)
开发者ID:AbdealiJK,项目名称:scikit-image,代码行数:9,代码来源:test_adapt_rgb.py

示例4: convertHSV

def convertHSV(img):
    "convert RGBA into HSV color Space"
    if img.shape[2]==4:
        return rgb2hsv(img[:,:,0:3])
    else:
        if img.shape[2]==3:
            return rgb2hsv(img)
        else:
            print ("Image format not supported")
开发者ID:dgormez,项目名称:pattern-recognition,代码行数:9,代码来源:pattern-reco.py

示例5: legendCurveDictionary

def legendCurveDictionary(legends, curveLocs):
    # print curveLocs
    curves = [(x.split("Curve-")[1].split(".png")[0], rgb2hsv(imread(x)) * 360) for x in curveLocs]
    lcd = {}
    for i, l in enumerate(legends):
        lcd[i] = [x for x in [curveScore(l, curve) for curve in curves] if x[1] is not None]
    return lcd
开发者ID:sagnik,项目名称:svg-linegraph-processing,代码行数:7,代码来源:CurveLegendAssociation.py

示例6: stretchImageHue

def stretchImageHue(imrgb):
	# Image must be stored as 0-1 bound float. If it's 0-255 int, convert
	if( imrgb.max() > 1 ):
		imrgb = imrgb*1./255

	# Transform to HSV
	imhsv = rgb2hsv(imrgb)

	# Find 2-98 percentiles of H histogram (except de-saturated pixels)
	plt.figure()
	plt.hist(imhsv[imhsv[:,:,1]>0.1,0].flatten(), bins=360)
	p2, p98 = np.percentile(imhsv[imhsv[:,:,1]>0.1,0], (2, 98))
	print p2, p98

	imhsv[:,:,0] = doStretch(imhsv[:,:,0], p2, p98, 0.6, 0.99)
	plt.figure()
	plt.hist(imhsv[imhsv[:,:,1]>0.1,0].flatten(), bins=360)	

	imrgb_stretched = hsv2rgb(imhsv)
	plt.figure()
	plt.imshow(imrgb)
	plt.figure()
	plt.imshow(imrgb_stretched)

	plt.show()
开发者ID:adfoucart,项目名称:deep-net-histology,代码行数:25,代码来源:huestretcher.py

示例7: run

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)
开发者ID:bootuz,项目名称:NCRF,代码行数:25,代码来源:tissue_mask.py

示例8: get_disease2

	def get_disease2(self):
		r,g,b = my_image.image_split(self.i_source)
		hsv = rgb2hsv(self.i_source)
		dise= np.copy(self.i_source[:,:,1])
		dise[dise>1]=0
		dise[(hsv[:,:,0]>0) & (hsv[:,:,0]<float(45.0/255))&(r<100)&(g<100)&(b<50)]=1
		label_im, nb_labels = ndimage.label(dise)
		sizes = ndimage.sum(dise, label_im, range(nb_labels + 1))
		mean_vals = ndimage.sum(dise, label_im, range(1, nb_labels + 1))
		mask_size = sizes < np.max(sizes)
		remove_pixel = mask_size[label_im]
		label_im[remove_pixel] = 0
		label_im[label_im>0]=1
		
#		pdb.set_trace()
		###
		# remove artifacts connected to image border
		self.s_disease = 0
		# label image regions
		region = regionprops(label(label_im))
		for r1 in region:
#			pdb.set_trace()
			if r1.area > 10:
				self.s_disease += r1.area
			else:
				minr, minc, maxr, maxc = r1.bbox
				label_im[float(minr):float(maxr),float(minc):float(maxc)]=0
							
		self.i_desease = label_im 
		self.i_leaf = self.i_source#blade
		self.i_back = self.i_source#background
		self.s_leaf = 1#s_b+s_d
开发者ID:A02l01,项目名称:Navautron,代码行数:32,代码来源:leaf.py

示例9: slic_data

def slic_data():
   for i in range(uu_num_train+uu_num_test):

      print "data %d" %(i+1)
      img_name = ''
      if i < 10:
         img_name = '0' + str(i)
      else:
         img_name = str(i)

      #Read first 70 images as floats
      img = img_as_float(io.imread('..\data\\training\image_2\uu_0000' + img_name + '.png'))
      img_hsv = color.rgb2hsv(img)
      gt_img = img_as_float(io.imread('..\data\\training\gt_image_2\uu_road_0000' + img_name + '.png'))

      #Create superpixels for training images
      image_segment = slic(img, n_segments = numSegments, sigma = 5)
      t, train_indices = np.unique(image_segment, return_index=True)
      images_train_indices.append(train_indices)
      image = np.reshape(img,(1,(img.shape[0]*img.shape[1]),3))
      image_hsv = np.reshape(img_hsv,(1,(img_hsv.shape[0]*img_hsv.shape[1]),3))
      #images_train.append([image[0][i] for i in train_indices])
      images_train_hsv.append([image_hsv[0][i] for i in train_indices])

      #Create gt training image values index at train_indices and converted to 1 or 0
      gt_image = np.reshape(gt_img, (1,(gt_img.shape[0]*gt_img.shape[1]),3))
      gt_image = [1 if gt_image[0][i][2] > 0 else 0 for i in train_indices]
      gt_images_train.append(gt_image)
开发者ID:rudasi,项目名称:road-classification,代码行数:28,代码来源:old_svm_creator.py

示例10: extract_descriptors_he

def extract_descriptors_he(_img, w_size, _ncpus=None):
    """
    EXRACT_LOCAL_DESCRIPTORS_HE: extracts a set of local descriptors of the image:
        - histogram of Hue values
        - histogram of haematoxylin and eosin planes
        - Gabor descriptors in haematoxylin and eosin spaces, respectively
        - local binary patterns in haematoxylin and eosin spaces, respectively

    :param _img: numpy.ndarray

    :param w_size: int

    :return: list
    """
    assert (_img.ndim == 3)

    img_iterator = sliding_window(_img.shape[:-1], (w_size, w_size), step=(w_size, w_size))  # non-overlapping windows
    gabor = GaborDescriptor()
    lbp   = LBPDescriptor()

    hsv = rgb2hsv(_img)
    h, e, _ = rgb2he2(_img)

    res = []
    with ProcessPoolExecutor(max_workers=_ncpus) as executor:
        for w_coords in img_iterator:
            res.append(executor.submit(_worker2, hsv[:,:,0], h, e, gabor, lbp, w_coords))

    desc = []
    for f in as_completed(res):
        desc.append(f.result())

    return desc
开发者ID:gitter-badger,项目名称:WSItk,代码行数:33,代码来源:extract.py

示例11: extr_beauty_ftrs

def extr_beauty_ftrs(imgFlNm):
	img = os.path.basename(imgFlNm)
	
	print("Extracting beauty features for %s" %imgFlNm)

	try:
		rgbImg = resize_img(io.imread(imgFlNm))
	except Exception as e:
		print("Invalid image")
		return e
		
	if len(rgbImg.shape) != 3 or rgbImg.shape[2] !=3:
		print("Invalid image.. Continuing..")
		final_ftr_obj_global[img] = None
		return None

	hsvImg = color.rgb2hsv(rgbImg)
	grayImg = color.rgb2gray(rgbImg)

	red, green, blue = get_arr(rgbImg)
	hue, saturation, value = get_arr(hsvImg)

	contrast = calc_contrast(red, green, blue)
	ftrs = calc_color_ftrs(hue, saturation, value)
	ftrs['contrast'] = contrast
	ftrs['entropy'] = entropy(grayImg) # added to include entropy of the given image: more details: http://stackoverflow.com/a/42059758/5759063
	ftrs.update(get_spat_arrng_ftrs(grayImg))
	
	final_ftr_obj_global[img] = ftrs
	
	return final_ftr_obj_global
开发者ID:smenon8,项目名称:AnimalWildlifeEstimator,代码行数:31,代码来源:ExtractBtyFtrs.py

示例12: RgbToPlateBackgroundScore

def RgbToPlateBackgroundScore(im):
	#This function compares images to find number plate background colour
	#since UK plates come in two different colours, they are merged into
	#a single score here.

	hsvImg = color.rgb2hsv(im)

	#Target colours
	#Yellow HSV 47/360, 81/100, 100/100 or 32/255, 217/255, > 248/255
	#While HSV None, < 8/100, > 82/100 or ?/255, < 21/255, > 255/255	

	#Compare to white
	whiteScore = (255.-hsvImg[:,:,1]) * (hsvImg[:,:,2]) / pow(255., 2.)
	
	#Compare to yellow
	#Hue is a repeating value similar to angle, compute dot product with yellow
	hueAng = hsvImg[:,:,0] * (2. * math.pi / 255.)
	hueSin = np.sin(hueAng)
	hueCos = np.cos(hueAng)
	targetSin = math.sin(math.radians(47.)) #Hue of yellow
	targetCos = math.cos(math.radians(47.))
	dotProd = hueSin * targetSin + hueCos * targetCos
	yellowHueScore = (dotProd + 1.) / 2. #Scale from 0 to 1	
	yellowSatScore = np.abs(hsvImg[:,:,1] - 217.) / 217.
	yellowValScore = hsvImg[:,:,2] / 255.
	yellowScore = yellowHueScore * yellowSatScore * yellowValScore

	scoreMax = np.maximum(whiteScore, yellowScore)
	return scoreMax
开发者ID:TimSC,项目名称:pyanpr,代码行数:29,代码来源:deskewMarkedPlates.py

示例13: loadData

    def loadData(self):
        self.rawData = io.imread(self.fileName, plugin='tifffile')
        self.rawData = cv2.merge((self.rawData[:, :, 0].T,
                                  self.rawData[:, :, 1].T,
                                  self.rawData[:, :, 2].T))
        self.cData = self.rawData.copy()
        self.grayData = self.rawData.copy()
        self.grayData = color.rgb2gray(self.rawData)
        self.hsvData = color.rgb2hsv(self.rawData)
        # self.grayData = self.grayData.convert('LA')
        # self.grayData = self.grayData.transpose(method=PIL.Image.TRANSPOSE)
        self.grayData = transform.rotate(self.grayData, angle=0)
        self.cData = transform.rotate(self.cData, angle=0)
        self.hsvData = transform.rotate(self.hsvData, angle=0)
        self.b = self.cData[:, :, 0]
        self.g = self.cData[:, :, 1]
        self.r = self.cData[:, :, 2]
        self.v = self.hsvData[:, :, 0]
        self.s = self.hsvData[:, :, 1]
        self.h = self.hsvData[:, :, 2]

        self.colorDict = {'RGB': self.cData,
                          'GRAY': self.grayData,
                          'B': self.b,
                          'G': self.g,
                          'R': self.r,
                          'HSV': self.hsvData,
                          'H': self.h,
                          'S': self.s,
                          'V': self.v}
开发者ID:MichalZG,项目名称:cellROI,代码行数:30,代码来源:cellroi.py

示例14: testPipo

 def testPipo(self):
     hsv = rgb2hsv(self.sample / 256.0).reshape((4, 3))
     print hsv
     polar = colors.convert(hsv, 0.0, 1.0)
     print polar
     xy = colors.unconvert(polar)
     print xy
开发者ID:athoune,项目名称:Palette,代码行数:7,代码来源:colors_test.py

示例15: ton_and_color_corrections

def ton_and_color_corrections():
    #色调和彩色校正
    image=data.astronaut()
    h1=color.rgb2hsv(image)
    h2=h1.copy()
    h1[:,:,1]=h1[:,:,1]*0.5
    image1=color.hsv2rgb(h1)
    h2[:,:,1]=h2[:,:,1]*0.5+0.5
    image2=color.hsv2rgb(h2)
    io.imshow(image)
    io.imsave('astronaut.png',image)
    io.imshow(image1)
    io.imsave('astronautlight.png',image1)
    io.imshow(image2)
    io.imsave('astronautdark.png',image2)
    
    imagered=image.copy()
    imagered[:,:,0]=image[:,:,0]*127.0/255+128
    io.imsave('astronautred.png',imagered)
    imageblue=image.copy()
    imageblue[:,:,2]=image[:,:,2]*127.0/255+128
    io.imsave('astronautblue.png',imageblue)
    imageyellow=image.copy()
    imageyellow[:,:,0]=image[:,:,0]*127.0/255+128
    imageyellow[:,:,1]=image[:,:,1]*127.0/255+128
    io.imsave('astronautyellow.png',imageyellow)
    io.imshow(imageyellow)
开发者ID:xingnix,项目名称:learning,代码行数:27,代码来源:colorimage.py


注:本文中的skimage.color.rgb2hsv函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。