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


Python color.rgb2gray方法代码示例

本文整理汇总了Python中skimage.color.rgb2gray方法的典型用法代码示例。如果您正苦于以下问题:Python color.rgb2gray方法的具体用法?Python color.rgb2gray怎么用?Python color.rgb2gray使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在skimage.color的用法示例。


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

示例1: test_luminance

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def test_luminance():
    source = sn.load('tests/sobel_input.png')[:,:,:3]

    L = rgb2gray(source)
    skresult = np.dstack([L, L, L])
    small_skresult = sn.resize(skresult, width=256)

    L = sn.rgb_to_luminance(source)
    snresult = np.dstack([L, L, L])
    small_snresult = sn.resize(snresult, width=256)

    L = skimage_sobel(source)
    sksobel = np.dstack([L, L, L])
    small_sksobel = sn.resize(sksobel, width=256)

    L = sn.rgb_to_luminance(source)
    L = sn.compute_sobel(L)
    snsobel = np.dstack([L, L, L])
    small_snsobel = sn.resize(snsobel, width=256)

    sn.show(np.hstack([
        small_skresult,
        small_snresult,
        small_sksobel,
        small_snsobel])) 
开发者ID:prideout,项目名称:snowy,代码行数:27,代码来源:test_color.py

示例2: convertToGrayScale

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def convertToGrayScale (rootDir, dirNames):
    nbConverted = 0
    for root, dirs, files in os.walk(rootDir):
        files.sort(key=tryint)
        for file in files:
            parentDir = os.path.basename(root)
            fname = os.path.splitext(file)[0]  # no path, no extension. only filename
            if parentDir in dirNames:
                # convert all images in here to grayscale, store to dirName_gray
                newDirPath = ''.join([os.path.dirname(root), os.sep, parentDir + "_gray"])
                newFilePath = ''.join([newDirPath, os.sep, fname + "_gray.jpg"])
                if not os.path.exists(newDirPath):
                    os.makedirs(newDirPath)
                if not os.path.exists(newFilePath):
                    # read in grayscale, write to new path
                    # with OpenCV: weird results (gray image larger than color ?!?)
                    # img = cv2.imread(root+os.sep+file, 0)
                    # cv2.imwrite(newFilePath, img)
                    
                    img_gray = rgb2gray(io.imread(root + os.sep + file))
                    io.imsave(newFilePath, img_gray)  # don't write to disk if already exists
                    nbConverted += 1
    
    # print(nbConverted, " files have been converted to Grayscale")
    return 0 
开发者ID:matthijsvk,项目名称:TCDTIMITprocessing,代码行数:27,代码来源:helpFunctions.py

示例3: colorize

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def colorize():
    path = './img/colorize/colorize2.png'
    # cv2.imwrite('./img/colorize3.png', cv2.imread(path, 0))
    x, y, image_shape = get_train_data(path)
    model = build_model()
    model.load_weights('./data/simple_colorize.h5')
    output = model.predict(x)
    output *= 128
    tmp = np.zeros((200, 200, 3))
    tmp[:, :, 0] = x[0][:, :, 0]
    tmp[:, :, 1:] = output[0]
    colorizePath = path.replace(".png", "-res.png")
    imsave(colorizePath, lab2rgb(tmp))
    cv2.imshow("I", cv2.imread(path))
    cv2.imshow("II", cv2.imread(colorizePath))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # imsave("test_image_gray.png", rgb2gray(lab2rgb(tmp))) 
开发者ID:vipstone,项目名称:faceai,代码行数:21,代码来源:colorize.py

示例4: load_image

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def load_image(filename, width, invert, gamma):
    # Read the image
    img = imageio.imread(filename)

    if img.shape[-1] == 4:
        # Blend the alpha channel
        img = color.rgba2rgb(img)

    # Grayscale
    img = color.rgb2gray(img)

    # Resample and adjust the aspect ratio
    width_px = (3 * width) * 16

    img_width = 1.0 * width_px
    img_height = int(img.shape[0] * 3 * (img_width / (4 * img.shape[1])))
    img = transform.resize(img, (img_height, img_width), anti_aliasing=True, mode='constant')

    # Adjust the exposure
    img = exposure.adjust_gamma(img, gamma)

    if invert:
        img = 1 - img

    return img 
开发者ID:hughpyle,项目名称:ASR33,代码行数:27,代码来源:image1.py

示例5: generate

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def generate(self, x_fixed, x_target_fixed, pose_target_fixed, root_path=None, path=None, idx=None, save=True):
        G = self.sess.run(self.G, {self.x: x_fixed, self.pose_target: pose_target_fixed})
        ssim_G_x_list = []
        # x_0_255 = utils_wgan.unprocess_image(x_target_fixed, 127.5, 127.5)
        for i in xrange(G.shape[0]):
            # G_gray = rgb2gray((G[i,:]/127.5-1).clip(min=-1,max=1))
            # x_target_gray = rgb2gray((x_target_fixed[i,:]).clip(min=-1,max=1))
            G_gray = rgb2gray((G[i,:]).clip(min=0,max=255).astype(np.uint8))
            x_target_gray = rgb2gray(((x_target_fixed[i,:]+1)*127.5).clip(min=0,max=255).astype(np.uint8))
            ssim_G_x_list.append(ssim(G_gray, x_target_gray, data_range=x_target_gray.max() - x_target_gray.min(), multichannel=False))
        ssim_G_x_mean = np.mean(ssim_G_x_list)
        if path is None and save:
            path = os.path.join(root_path, '{}_G_ssim{}.png'.format(idx,ssim_G_x_mean))
            save_image(G, path)
            print("[*] Samples saved: {}".format(path))
        return G 
开发者ID:charliememory,项目名称:Pose-Guided-Person-Image-Generation,代码行数:18,代码来源:trainer.py

示例6: generate

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def generate(self, x_fixed, x_target_fixed, pose_fixed, part_bbox_fixed, root_path=None, path=None, idx=None, save=True):
        G_pose_rcv, G_pose = self.sess.run([self.G_pose_rcv, self.G_pose])
        G_pose_inflated = py_poseInflate(G_pose_rcv, is_normalized=True, radius=4, img_H=256, img_W=256)
        # G = self.sess.run(self.G, {self.x: x_fixed, self.G_pose_inflated: G_pose_inflated, self.part_bbox: part_bbox_fixed})
        G_pose_inflated_img = np.tile(np.amax((G_pose_inflated+1)*127.5, axis=-1, keepdims=True), [1,1,1,3])
        
        # ssim_G_x_list = []
        # for i in xrange(G_pose.shape[0]):
        #     G_gray = rgb2gray((G[i,:]).clip(min=0,max=255).astype(np.uint8))
        #     x_gray = rgb2gray(((x_fixed[i,:]+1)*127.5).clip(min=0,max=255).astype(np.uint8))
        #     ssim_G_x_list.append(ssim(G_gray, x_gray, data_range=x_gray.max() - x_gray.min(), multichannel=False))
        # ssim_G_x_mean = np.mean(ssim_G_x_list)
        if path is None and save:
            # path = os.path.join(root_path, '{}_G_ssim{}.png'.format(idx,ssim_G_x_mean))
            # save_image(G, path)
            # print("[*] Samples saved: {}".format(path))
            path = os.path.join(root_path, '{}_G_pose.png'.format(idx))
            save_image(G_pose, path)
            print("[*] Samples saved: {}".format(path))
            path = os.path.join(root_path, '{}_G_pose_inflated.png'.format(idx))
            save_image(G_pose_inflated_img, path)
            print("[*] Samples saved: {}".format(path))
        return G_pose 
开发者ID:charliememory,项目名称:Disentangled-Person-Image-Generation,代码行数:25,代码来源:trainer.py

示例7: get_resized_image

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def get_resized_image(file, ratio):
    img = util.img_as_float(io.imread(file))
    if len(img.shape) >= 3 and img.shape[2] == 4:
        img = color.rgba2rgb(img)
    if len(img.shape) == 2:
        img = color.gray2rgb(img)

    eimg = filters.sobel(color.rgb2gray(img))
    width = img.shape[1]
    height = img.shape[0]

    mode, rm_paths = get_lines_to_remove((width, height), ratio)
    if mode:
        logger.debug("Carving %s %s paths ", rm_paths, mode)
        outh = transform.seam_carve(img, eimg, mode, rm_paths)
        return outh
    else:
        return img 
开发者ID:ftramer,项目名称:ad-versarial,代码行数:20,代码来源:generator.py

示例8: levelset_segment_theano

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def levelset_segment_theano(img, phi=None, dt=1, v=1, sigma=1, alpha=1, n_iter=80):
    img = color.rgb2gray(img)

    img_smooth = scipy.ndimage.filters.gaussian_filter(img, sigma)

    if phi is None:
        phi = default_phi(img)

    phi = levelset_evolution(img_smooth, phi, dt, v, alpha, n_iter)

    return (phi < 0) 
开发者ID:wiseodd,项目名称:cnn-levelset,代码行数:13,代码来源:segmenter.py

示例9: __init__

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def __init__(self, fname, format=None, resize=None, anti_aliasing=False,
                 electrodes=None, metadata=None, compress=False,
                 interp_method='linear', extrapolate=False):
        # Open the video reader:
        reader = video_reader(fname, format=format)
        # Combine video metadata with user-specified metadata:
        meta = reader.get_meta_data()
        if metadata is not None:
            meta.update(metadata)
        meta['source'] = fname
        # Read the video:
        vid = [frame for frame in reader]
        # Consider downscaling before doing anything else (with anti-aliasing,
        # this can take a while):
        if resize is not None:
            vid = parfor(img_resize, vid, func_args=[resize],
                         func_kwargs={'anti_aliasing': anti_aliasing})
        if vid[0].ndim == 3 and vid[0].shape[-1] == 3:
            vid = parfor(rgb2gray, vid)
        vid = np.array(parfor(img_as_float, vid)).transpose((1, 2, 0))
        # Infer the time points from the video frame rate:
        n_frames = vid.shape[-1]
        time = np.arange(n_frames) * meta['fps']
        # Call the Stimulus constructor:
        super(VideoStimulus, self).__init__(vid.reshape((-1, n_frames)),
                                            time=time, electrodes=electrodes,
                                            metadata=meta, compress=compress,
                                            interp_method=interp_method,
                                            extrapolate=extrapolate) 
开发者ID:pulse2percept,项目名称:pulse2percept,代码行数:31,代码来源:videos.py

示例10: __init__

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def __init__(self, source, format=None, resize=None, as_gray=False,
                 electrodes=None, metadata=None, compress=False):
        if metadata is None:
            metadata = {}
        if isinstance(source, str):
            # Filename provided:
            img = imread(source, format=format)
            metadata['source'] = source
            metadata['source_shape'] = img.shape
        elif isinstance(source, ImageStimulus):
            img = source.data.reshape(source.img_shape)
            metadata.update(source.metadata)
            if electrodes is None:
                electrodes = source.electrodes
        elif isinstance(source, np.ndarray):
            img = source
        else:
            raise TypeError("Source must be a filename or another "
                            "ImageStimulus, not %s." % type(source))
        if img.ndim < 2 or img.ndim > 3:
            raise ValueError("Images must have 2 or 3 dimensions, not "
                             "%d." % img.ndim)
        # Convert to grayscale if necessary:
        if as_gray:
            if img.ndim == 3 and img.shape[2] == 4:
                # Blend the background with black:
                img = rgba2rgb(img, background=(0, 0, 0))
            img = rgb2gray(img)
        # Resize if necessary:
        if resize is not None:
            img = img_resize(img, resize)
        # Store the original image shape for resizing and color conversion:
        self.img_shape = img.shape
        # Convert to float array in [0, 1] and call the Stimulus constructor:
        super(ImageStimulus, self).__init__(img_as_float32(img).ravel(),
                                            time=None, electrodes=electrodes,
                                            metadata=metadata,
                                            compress=compress) 
开发者ID:pulse2percept,项目名称:pulse2percept,代码行数:40,代码来源:images.py

示例11: rgb2gray

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def rgb2gray(self, electrodes=None):
        """Convert the image to grayscale

        Parameters
        ----------
        electrodes : int, string or list thereof; optional
            Optionally, you can provide your own electrode names. If none are
            given, electrode names will be numbered 0..N.

            .. note::
               The number of electrode names provided must match the number of
               pixels in the grayscale image.

        Returns
        -------
        stim : `ImageStimulus`
            A copy of the stimulus object with all grayscale values inverted
            in the range [0, 1].

        Notes
        -----
        *  A four-channel image is interpreted as RGBA (e.g., a PNG), and the
           alpha channel will be blended with the color black.

        """
        img = self.data.reshape(self.img_shape)
        if img.ndim == 3 and img.shape[2] == 4:
            # Blend the background with black:
            img = rgba2rgb(img, background=(0, 0, 0))
        return ImageStimulus(rgb2gray(img), electrodes=electrodes,
                             metadata=self.metadata) 
开发者ID:pulse2percept,项目名称:pulse2percept,代码行数:33,代码来源:images.py

示例12: _create_data

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def _create_data(self):
        root = utils.get_data_root()
        path = os.path.join(root, 'faces', self.name + '.jpg')
        try:
            image = io.imread(path)
        except FileNotFoundError:
            raise RuntimeError('Unknown face name: {}'.format(self.name))
        image = color.rgb2gray(image)
        self.image = transform.resize(image, [512, 512])

        grid = np.array([
            (x, y) for x in range(self.image.shape[0]) for y in range(self.image.shape[1])
        ])

        rotation_matrix = np.array([
            [0, -1],
            [1, 0]
        ])
        p = self.image.reshape(-1) / sum(self.image.reshape(-1))
        ix = np.random.choice(range(len(grid)), size=self.num_points, replace=True, p=p)
        points = grid[ix].astype(np.float32)
        points += np.random.rand(self.num_points, 2)  # dequantize
        points /= (self.image.shape[0])  # scale to [0, 1]
        # assert 0 <= min(points) <= max(points) <= 1

        self.data = torch.tensor(points @ rotation_matrix).float()
        self.data[:, 1] += 1 
开发者ID:bayesiains,项目名称:nsf,代码行数:29,代码来源:plane.py

示例13: pre_processing

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def pre_processing(next_observe, observe):
    processed_observe = np.maximum(next_observe, observe)
    processed_observe = np.uint8(
        resize(rgb2gray(processed_observe), (84, 84), mode='constant') * 255)
    return processed_observe 
开发者ID:rlcode,项目名称:reinforcement-learning-kr,代码行数:7,代码来源:play_a3c_model.py

示例14: pre_processing

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def pre_processing(observe):
    processed_observe = np.uint8(
        resize(rgb2gray(observe), (84, 84), mode='constant') * 255)
    return processed_observe 
开发者ID:rlcode,项目名称:reinforcement-learning-kr,代码行数:6,代码来源:breakout_dqn.py

示例15: greyscale

# 需要导入模块: from skimage import color [as 别名]
# 或者: from skimage.color import rgb2gray [as 别名]
def greyscale(img):
    try:
        from skimage import img_as_ubyte
        from skimage.color import rgb2gray
    except ImportError:
        logger.error(
            ' scikit-image is not installed. '
            'In order to install all image feature dependencies run '
            'pip install ludwig[image]'
        )
        sys.exit(-1)

    return np.expand_dims(img_as_ubyte(rgb2gray(img)), axis=2) 
开发者ID:uber,项目名称:ludwig,代码行数:15,代码来源:image_utils.py


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