当前位置:网站首页>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()

边栏推荐
- Three. JS series (2): API structure diagram-2
- QT视频传输
- Seaborn数据可视化
- 最新Android面试合集,android视频提取音频
- LeetCode 1043. Separate the array to get the maximum and daily questions
- AutoLISP series (1): function function 1
- 字节跳动高工面试,轻松入门flutter
- LeetCode 1626. 无矛盾的最佳球队 每日一题
- DAPP defi NFT LP single and dual currency liquidity mining system development details and source code
- LeetCode 1049. 最后一块石头的重量 II 每日一题
猜你喜欢
随机推荐
作为Android开发程序员,android高级面试
【DesignMode】享元模式(Flyweight Pattern)
LeetCode 1654. 到家的最少跳跃次数 每日一题
os、sys、random标准库主要功能
LeetCode 1186. 删除一次得到子数组最大和 每日一题
编程模式-表驱动编程
LeetCode 1043. Separate the array to get the maximum and daily questions
Process from creation to encapsulation of custom controls in QT to toolbar (I): creation of custom controls
蓝桥杯 决赛 异或变换 100分
【DesignMode】外观模式 (facade patterns)
Lowcode: four ways to help transportation companies enhance supply chain management
ByteDance Android gold, silver and four analysis, Android interview question app
[medical segmentation] attention Unet
掌握这个提升路径,面试资料分享
LeetCode 312. Poke balloon daily
QT picture background color pixel processing method
A tour of gRPC:03 - proto序列化/反序列化
Binary search tree (features)
ORACLE进阶(六)ORACLE expdp/impdp详解
[C language] question set of X


![[designmode] proxy pattern](/img/ed/642aebc7b49cbf4d30b517665b2438.png)





