python库skimage给灰度图像染色的方法示例

灰度图像染成红色和黄色

# 1.将灰度图像转换为RGB图像
image = color.gray2rgb(grayscale_image)
# 2.保留红色分量和黄色分量
red_multiplier = [1, 0, 0]
yellow_multiplier = [1, 1, 0]
# 3.显示图像
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4),
                sharex=True, sharey=True)
ax1.imshow(red_multiplier * image)
ax2.imshow(yellow_multiplier * image)

HSV图像,H从0到1表示的颜色

hue_gradient = np.linspace(0, 1)
# print(hue_gradient.shape) # output:(50,)
hsv = np.ones(shape=(1, len(hue_gradient), 3), dtype=float)
hsv[:, :, 0] = hue_gradient

all_hues = color.hsv2rgb(hsv)

fig, ax = plt.subplots(figsize=(5, 2))
# Set image extent so hues go from 0 to 1 and the image is a nice aspect ratio.
ax.imshow(all_hues, extent=(0, 1, 0, 0.2))
ax.set_axis_off()

将灰度图像染成不同的颜色

hue_rotations = np.linspace(0, 1, 6)

fig, axes = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True)

for ax, hue in zip(axes.flat, hue_rotations):
  # Turn down the saturation to give it that vintage look.
  tinted_image = colorize(image, hue, saturation=0.3)
  ax.imshow(tinted_image, vmin=0, vmax=1)
  ax.set_axis_off()
fig.tight_layout()

完整代码

"""
=========================
Tinting gray-scale images
=========================

It can be useful to artificially tint an image with some color, either to
highlight particular regions of an image or maybe just to liven up a grayscale
image. This example demonstrates image-tinting by scaling RGB values and by
adjusting colors in the HSV color-space.

In 2D, color images are often represented in RGB---3 layers of 2D arrays, where
the 3 layers represent (R)ed, (G)reen and (B)lue channels of the image. The
simplest way of getting a tinted image is to set each RGB channel to the
grayscale image scaled by a different multiplier for each channel. For example,
multiplying the green and blue channels by 0 leaves only the red channel and
produces a bright red image. Similarly, zeroing-out the blue channel leaves
only the red and green channels, which combine to form yellow.
"""

import matplotlib.pyplot as plt
from skimage import data
from skimage import color
from skimage import img_as_float

grayscale_image = img_as_float(data.camera()[::2, ::2])
image = color.gray2rgb(grayscale_image)

red_multiplier = [1, 0, 0]
yellow_multiplier = [1, 1, 0]

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4),
                sharex=True, sharey=True)
ax1.imshow(red_multiplier * image)
ax2.imshow(yellow_multiplier * image)

######################################################################
# In many cases, dealing with RGB values may not be ideal. Because of that,
# there are many other `color spaces`_ in which you can represent a color
# image. One popular color space is called HSV, which represents hue (~the
# color), saturation (~colorfulness), and value (~brightness). For example, a
# color (hue) might be green, but its saturation is how intense that green is
# ---where olive is on the low end and neon on the high end.
#
# In some implementations, the hue in HSV goes from 0 to 360, since hues wrap
# around in a circle. In scikit-image, however, hues are float values from 0
# to 1, so that hue, saturation, and value all share the same scale.
#
# .. _color spaces:
#   https://en.wikipedia.org/wiki/List_of_color_spaces_and_their_uses
#
# Below, we plot a linear gradient in the hue, with the saturation and value
# turned all the way up:
import numpy as np

hue_gradient = np.linspace(0, 1)
# print(hue_gradient.shape) # output:(50,)
hsv = np.ones(shape=(1, len(hue_gradient), 3), dtype=float)
hsv[:, :, 0] = hue_gradient

all_hues = color.hsv2rgb(hsv)

fig, ax = plt.subplots(figsize=(5, 2))
# Set image extent so hues go from 0 to 1 and the image is a nice aspect ratio.
ax.imshow(all_hues, extent=(0, 1, 0, 0.2))
ax.set_axis_off()

######################################################################
# Notice how the colors at the far left and far right are the same. That
# reflects the fact that the hues wrap around like the color wheel (see HSV_
# for more info).
#
# .. _HSV: https://en.wikipedia.org/wiki/HSL_and_HSV
#
# Now, let's create a little utility function to take an RGB image and:
#
# 1. Transform the RGB image to HSV 2. Set the hue and saturation 3.
# Transform the HSV image back to RGB

def colorize(image, hue, saturation=1):
  """ Add color of the given hue to an RGB image.

  By default, set the saturation to 1 so that the colors pop!
  """
  hsv = color.rgb2hsv(image)
  hsv[:, :, 1] = saturation
  hsv[:, :, 0] = hue
  return color.hsv2rgb(hsv)

######################################################################
# Notice that we need to bump up the saturation; images with zero saturation
# are grayscale, so we need to a non-zero value to actually see the color
# we've set.
#
# Using the function above, we plot six images with a linear gradient in the
# hue and a non-zero saturation:

hue_rotations = np.linspace(0, 1, 6)

fig, axes = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True)

for ax, hue in zip(axes.flat, hue_rotations):
  # Turn down the saturation to give it that vintage look.
  tinted_image = colorize(image, hue, saturation=0.3)
  ax.imshow(tinted_image, vmin=0, vmax=1)
  ax.set_axis_off()
fig.tight_layout()

######################################################################
# You can combine this tinting effect with numpy slicing and fancy-indexing
# to selectively tint your images. In the example below, we set the hue of
# some rectangles using slicing and scale the RGB values of some pixels found
# by thresholding. In practice, you might want to define a region for tinting
# based on segmentation results or blob detection methods.

from skimage.filters import rank

# Square regions defined as slices over the first two dimensions.
top_left = (slice(100),) * 2
bottom_right = (slice(-100, None),) * 2

sliced_image = image.copy()
sliced_image[top_left] = colorize(image[top_left], 0.82, saturation=0.5)
sliced_image[bottom_right] = colorize(image[bottom_right], 0.5, saturation=0.5)

# Create a mask selecting regions with interesting texture.
noisy = rank.entropy(grayscale_image, np.ones((9, 9)))
textured_regions = noisy > 4
# Note that using `colorize` here is a bit more difficult, since `rgb2hsv`
# expects an RGB image (height x width x channel), but fancy-indexing returns
# a set of RGB pixels (# pixels x channel).
masked_image = image.copy()
masked_image[textured_regions, :] *= red_multiplier

fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4),
                sharex=True, sharey=True)
ax1.imshow(sliced_image)
ax2.imshow(masked_image)

plt.show()

######################################################################
# For coloring multiple regions, you may also be interested in
# `skimage.color.label2rgb http://scikit-
# image.org/docs/0.9.x/api/skimage.color.html#label2rgb`_.

到此这篇关于python库skimage给灰度图像染色的方法示例的文章就介绍到这了,更多相关python 灰度图像染色内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python实现图片二值化及灰度处理方式

    我就废话不多说了,直接上代码吧! 集成环境:win10 pycharm #!/usr/bin/env python3.5.2 # -*- coding: utf-8 -*- '''4图片灰度调整及二值化: 集成环境:win10 python3 Pycharm ''' from PIL import Image # load a color image im = Image.open('picture\\haha.png' )#当前目录创建picture文件夹 # convert to grey

  • python实现彩色图转换成灰度图

    本文实例为大家分享了python实现彩色图转换成灰度图的具体代码,供大家参考,具体内容如下 from PIL import Image import os # 图像组成:红绿蓝 (RGB)三原色组成 亮度(255,255,255) image = "Annie1.jpg" img = Image.open(image) img_all = "素描" + image new = Image.new("L", img.size, 255) width

  • Python批量将图片灰度化的实现代码

    技术关键 os 模块的使用 使用 os.getcwd 获取当前路径 使用 os.listdir()获取文件列表 使用 os.path.splitext() 分割文件名和扩展名 使用 PLI 的 convert('L') 方法将图片转为灰度 代码实现 from PIL import Image import os path = os.getcwd() # 获取当前路径 file_list = os.listdir() for file in file_list: filename = os.pat

  • python-OpenCV 实现将数组转换成灰度图和彩图

    主要步骤 1.生成普通python数组(bytearray(),os.urandom()) 2.转换成numpy数组(numpy.array()) 3.通过reshape将数组转换到所需的维数 4.以图像的形式显示出来(cv.imshow()) 代码 import os import cv2 as cv import numpy as np # Make an array of 120000 random bytes randomByteArray = bytearray(os.urandom(

  • Python 将RGB图像转换为Pytho灰度图像的实例

    问题: 我正尝试使用matplotlib读取RGB图像并将其转换为灰度. 在matlab中,我使用这个: img = rgb2gray(imread('image.png')); 在matplotlib tutorial中他们没有覆盖它.他们只是在图像中阅读 import matplotlib.image as mpimg img = mpimg.imread('image.png') 然后他们切片数组,但是这不是从我所了解的将RGB转换为灰度. lum_img = img[:,:,0] 编辑:

  • Python cv2 图像自适应灰度直方图均衡化处理方法

    __author__ = 'Administrator' import numpy as np import cv2 mri_img = np.load('mri_img.npy') # normalization mri_max = np.amax(mri_img) mri_min = np.amin(mri_img) mri_img = ((mri_img-mri_min)/(mri_max-mri_min))*255 mri_img = mri_img.astype('uint8') r,

  • Python读取MRI并显示为灰度图像实例代码

    本文实例主要关于Python实现读取MRI(核磁共振成像)为numpy数组,使用imshow显示为灰度. 代码如下: import matplotlib.pyplot as plt import matplotlib.cbook as cbook import matplotlib.cm as cm import numpy as np # Data are 256x256 16 bit integers with cbook.get_sample_data('s1045.ima.gz') as

  • python 实现12bit灰度图像映射到8bit显示的方法

    图像显示和打印面临的一个问题是:图像的亮度和对比度能否充分突出关键部分.这里所指的"关键部分"在 CT 里的例子有软组织.骨头.脑组织.肺.腹部等等. 技术问题 1.显示器往往只有 8-bit, 而数据有 12- 至 16-bits. 2.如果将数据的 min 和 max 间 (dynamic range) 的之间转换到 8-bit 0-255 去,过程是个有损转换, 而且出来的图像往往突出的是些噪音. 算法分析 12-bit 到 8-bit 直接转换: computeMinMax(p

  • python opencv将图片转为灰度图的方法示例

    使用opencv将图片转为灰度图主要有两种方法,第一种是将彩色图转为灰度图,第二种是在使用OpenCV读取图片的时候直接读取为灰度图. 将彩色图转为灰度图 import cv2 import numpy as np if __name__ == "__main__": img_path = "timg.jpg" img = cv2.imread(img_path) #获取图片的宽和高 width,height = img.shape[:2][::-1] #将图片缩小

  • python库skimage给灰度图像染色的方法示例

    灰度图像染成红色和黄色 # 1.将灰度图像转换为RGB图像 image = color.gray2rgb(grayscale_image) # 2.保留红色分量和黄色分量 red_multiplier = [1, 0, 0] yellow_multiplier = [1, 1, 0] # 3.显示图像 fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4), sharex=True, sharey=True) ax1.imshow(red_m

  • 利用Python库Scapy解析pcap文件的方法

    每次写博客都是源于纳闷,python解析pcap这么常用的例子网上竟然没有,全是一堆命令行执行的python,能用吗?玩呢? pip安装scapy,然后解析pcap: import scapy from scapy.all import * from scapy.utils import PcapReader packets=rdpcap("./test.pcap") for data in packets: if 'UDP' in data: s = repr(data) print

  • python使用selenium爬虫知乎的方法示例

    说起爬虫一般想到的情况是,使用 python 中都通过 requests 库获取网页内容,然后通过 beautifulSoup 进行筛选文档中的标签和内容.但是这样有个问题就是,容易被反扒机制所拦住. 反扒机制有很多种,例如知乎:刚开始只加载几个问题,当你往下滚动时才会继续往下面加载,而且在往下滚动一段距离时就会出来一个登陆的弹框. 这样的机制对于通过获取服务器返回内容的爬虫方式进行了限制,我们只能获得前几个回答,而没办法或许后面的回答. 所以需要使用 selenium 模拟真实浏览器进行操作.

  • Python脚本读取Consul配置信息的方法示例

    先来说一下背景,为什么要写脚本去读Consul的配置信息呢?Consul是啥呢?consul是google开源的一个使用go语言开发的服务发现.配置管理中心服务.目前公司用的是这个东西去管理项目上的一些配置信息.公司的环境是通过docker镜像的方式去部署的,镜像是通过rancher去进行管理的.这一套东西面临的一个问题是:服务每次更新之后,服务对应的ip地址是动态变化的.每次需要使用swagger去测接口的时候,都要去rancher上去重新找新的ip地址,比较麻烦.正好呢,最近部门在考虑准备做

  • python实现提取jira bug列表的方法示例

    目录 公司要求内部每日整理jira bug发邮件,手动执行了一段时间,想着用自动化的方式实现,故用了3天的时间做出了此脚本. 第一版基础版 # -*- coding:utf-8 -*- import requests import re from bs4 import BeautifulSoup as bs import time import os jql = "project = SDP and parent = SDP-13330 AND issuetype in (standardIss

  • Python实现检测文件MD5值的方法示例

    本文实例讲述了Python实现检测文件MD5值的方法.分享给大家供大家参考,具体如下: 前面介绍过Python计算文件md5值的方法,这里分析一下Python检测文件MD5值的另一种实现方法. 概述: MD5(单向散列算法)的全称是Message-Digest Algorithm 5(信息-摘要算法),经MD2.MD3和MD4发展而来.MD5算法的使用不需要支付任何版权费用. 实现代码: #python 检测文件MD5值 #python version 2.6 import hashlib im

  • Python简单计算文件MD5值的方法示例

    本文实例讲述了Python简单计算文件MD5值的方法.分享给大家供大家参考,具体如下: 一 代码 import sys import hashlib import os.path filename = sys.argv[1] if os.path.isfile(filename): fp=open(filename,'rb') contents=fp.read() fp.close() print(hashlib.md5(contents).hexdigest()) else: print('f

  • 纯python进行矩阵的相乘运算的方法示例

    本文介绍了纯python进行矩阵的相乘运算的方法示例,分享给大家,具体如下: def matrixMultiply(A, B): # 获取A的行数和列数 A_row, A_col = shape(A) # 获取B的行数和列数 B_row, B_col = shape(B) # 不能运算情况的判断 if(A_col != B_row): raise ValueError # 最终的矩阵 result = [] # zip 解包后是转置后的元组,强转成list, 存入result中 BT = [li

  • Python统计列表元素出现次数的方法示例

    1. 引言 在使用Python的时候,通常会出现如下场景: array = [1, 2, 3, 3, 2, 1, 0, 2] 获取array中元素的出现次数 比如,上述列表中:0出现了1次,1出现了2次,2出现了3次,3出现了2次. 本文阐述了Python获取元素出现次数的几种方法.点击获取完整代码. 2. 方法 获取元素出现次数的方法较多,这里我提出如下5个方法,谨供参考.下面的代码,传入的参数均为 array = [1, 2, 3, 3, 2, 1, 0, 2] 2.1 Counter方法

  • Python基于Matplotlib库简单绘制折线图的方法示例

    本文实例讲述了Python基于Matplotlib库简单绘制折线图的方法.分享给大家供大家参考,具体如下: Matplotlib画折线图,有一些离散点,想看看这些点的变动趋势: import matplotlib.pyplot as plt x1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] y1=[30,31,31,32,33,35,35,40,47,62,99,186,480] x2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1

随机推荐