当前位置:网站首页>Skimage learning (1)
Skimage learning (1)
2022-07-07 17:02:00 【Original knowledge】
1、 Generate structured elements
This example shows how to use skimage The function in . Generate morphology of structural elements . The title of each graph represents the function call .
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage.morphology import (square, rectangle, diamond, disk, cube,
octahedron, ball, octagon, star)
# Square 、 Rectangle 、 The diamond 、 The disk 、 Cube 、 Octahedron 、 sphere 、 Octagon 、 Stars
# Generate 2D and 3D structuring elements.
struc_2d = {
"square(15)": square(15),
"rectangle(15, 10)": rectangle(15, 10),
"diamond(7)": diamond(7),
"disk(7)": disk(7),
"octagon(7, 4)": octagon(7, 4),
"star(5)": star(5)
}
struc_3d = {
"cube(11)": cube(11),
"octahedron(5)": octahedron(5),
"ball(5)": ball(35),
"ball(5)": ball(35),
}
# Visualize the elements.
fig = plt.figure(figsize=(8, 8))
idx = 1
#tems() Function returns a list of traversable ( Key value ) Tuple array .
''' plt.text(x, y, string, weight="bold", color="b") x: Abscissa of the location of the content of the note text y: The ordinate of the location where the annotation text content is located string: Note text content ,struc[i, j] number 0、1 weight: Thickness style of annotation text content '''
for title, struc in struc_2d.items():
ax = fig.add_subplot(4, 4, idx)#3 That's ok 3 Column , The position is
ax.imshow(struc, cmap="Greens", vmin=0, vmax=12)#ax Parameters are used to limit the range of values , Only will vmin and vmax Mapping values between , Usage is as follows
for i in range(struc.shape[0]):
for j in range(struc.shape[1]):
ax.text(j, i, struc[i, j], ha="center", va="center", color="w")
ax.set_axis_off()
ax.set_title(title)
idx += 1
for title, struc in struc_3d.items():
ax = fig.add_subplot(4, 4, idx, projection=Axes3D.name)
ax.voxels(struc)
ax.set_title(title)
idx += 1
fig.tight_layout()
plt.show()
2、 Images / Block view on array
This example demonstrates skimage.util() Medium view_as_blocks Use . When one wants to perform local operations on non overlapping image blocks , Block views are very useful . We use it skimage Medium astronaut. data , And its “ segmentation ” For all aspects . then , On each block , We can either gather the average value of this block , Maximum or median . The results are displayed together , Zoom the original astronaut image together with a third-order spline interpolation .
import numpy as np
from scipy import ndimage as ndi
from matplotlib import pyplot as plt
import matplotlib.cm as cm
from skimage import data
from skimage import color
from skimage.util import view_as_blocks
# get astronaut from skimage.data in grayscale
l = color.rgb2gray(data.astronaut())
#img=skimage.io.imread('11.jpg',)
#l = color.rgb2gray(img)
# size of blocks
block_shape = (4,4)
# Divide the astronaut picture into matrix blocks ( The size is block_shape)
view = view_as_blocks(l, block_shape)
# The last two dimensions merge into one , Become an array for easy operation
#img.shape[0]: The vertical size of the image ( Height ) img.shape[1]: The horizontal size of the image ( Width )
flatten_view = view.reshape(view.shape[0], view.shape[1], -1)
# By taking the “ mean value ”、“ Maximum ” or “ The median ” Resample the image .mean() The functionality : Find the mean
mean_view = np.mean(flatten_view, axis=2)
max_view = np.max(flatten_view, axis=2)
median_view = np.median(flatten_view, axis=2)
# Draw a subgraph ,sharex and sharey: surface ⽰ Whether the attributes of the coordinate axis are the same
fig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)
ax = axes.ravel()# Flatten the multidimensional data to ⼀ D data , It is equivalent to reshape(-1, order=order) .
''' https://vimsky.com/examples/usage/python-scipy.ndimage.zoom.html https://www.jianshu.com/p/909851f46411 ndi.zoom(input,zoom,output=None,order,mode='constant',cval=0.0,prefilter=True) Scale the array . Scale the array using spline interpolation in the requested order . input: Input pictures as an array zoom: Floating point numbers or arrays . If it's a floating point number , Zoom in and out the same multiple for each axis . If it's an array , Then assign a value to each axis . output: Output , The default is None order: integer ( Range 0-5) The order of spline interpolation , The default is 3. See later '''
l_resized = ndi.zoom(l, 2, order=3)
ax[0].set_title("Original rescaled with\n spline interpolation (order=3)")
ax[0].imshow(l_resized, extent=(-0.5, 128.5, 128.5, -0.5),
cmap=cm.Greys_r)
ax[1].set_title("Block view with\n local mean pooling")
ax[1].imshow(mean_view, cmap=cm.Greys_r)
ax[2].set_title("Block view with\n local max pooling")
ax[2].imshow(max_view, cmap=cm.Greys_r)
ax[3].set_title("Block view with\n local median pooling")
ax[3].imshow(median_view, cmap=cm.Greys_r)
for a in ax:
a.set_axis_off()
fig.tight_layout()
plt.show()
3、 Easy to use NumPy Operation to process images
This script explains how to use the basic NumPy operation , For example, slice 、 Shielding and fancy indexing , To modify the pixel value of the image .
# Use basic NumPy operation , For example, slice 、 Shielding and fancy indexing , To modify the pixel value of the image .
import numpy as np
from skimage import data
import matplotlib.pyplot as plt
# Read in ,camera yes ndarray Array of
camera = data.camera()
camera[:10] = 0# The first 0-9 Set as 0
mask = camera < 87#‘< ’ For conditional statements , Only return “ True and false ”. take camera Medium pixel value <87 The position of is marked as true, Others are false
camera[mask] = 255# recycling mask Marked position (true and false), Will be worth true The value of the set 255
inds_x = np.arange(len(camera))# Abscissa 0-511,arange(a,b,c) Function generation a~b( barring b), The interval is c An array of , ginseng 511 End point , Starting point 0, Step size is the default value 1.
inds_y = (4 * inds_x) % len(camera)# The generation step is 4 Array of , Ordinate
camera[inds_x, inds_y] = 0 # Press inds_x, inds_y The value of sets the pixel to zero
l_x, l_y = camera.shape[0], camera.shape[1]# Read the matrix length
print(l_x,l_y)
X, Y = np.ogrid[:l_x, :l_y]# Produce two long 512 Two dimensional array of
print(X,Y)
outer_disk_mask = (X - l_x / 2)**2 + (Y - l_y / 2)**2 > (l_x / 2)**2# Generate circular grid coordinates
camera[outer_disk_mask] = 0 # Assign , Everything except circles turns black
plt.figure(figsize=(4, 4)) # establish figure The size ratio of
plt.imshow(camera, cmap='gray') # Display images
plt.axis('off')
plt.show()
边栏推荐
猜你喜欢
最新高频Android面试题目分享,带你一起探究Android事件分发机制
最新Android高级面试题汇总,Android面试题及答案
DNS 系列(一):为什么更新了 DNS 记录不生效?
Master this promotion path and share interview materials
Arduino 控制的双足机器人
AutoLISP series (2): function function 2
Seaborn数据可视化
Module VI
Sort out several important Android knowledge and advanced Android development interview questions
两类更新丢失及解决办法
随机推荐
LeetCode 152. 乘积最大子数组 每日一题
LeetCode 1155. 掷骰子的N种方法 每日一题
如何在软件研发阶段落地安全实践
Localstorage and sessionstorage
[PHP] PHP interface inheritance and interface multi inheritance principle and implementation method
水平垂直居中 方法 和兼容
最新2022年Android大厂面试经验,安卓View+Handler+Binder
ORACLE进阶(六)ORACLE expdp/impdp详解
浅浅理解.net core的路由
Talk about the realization of authority control and transaction record function of SAP system
QT video transmission
Sqlserver2014+: create indexes while creating tables
LeetCode 1696. 跳跃游戏 VI 每日一题
LeetCode 1186. Delete once to get the sub array maximum and daily question
Opencv configuration 2019vs
LeetCode 1186. 删除一次得到子数组最大和 每日一题
使用JSON.stringify()去实现深拷贝,要小心哦,可能有巨坑
Build an all in one application development platform, light flow, and establish a code free industry benchmark
LeetCode 1155. N ways to roll dice one question per day
模块六