Python image processing one: image reading, display and storage

Image reading, display and storage

skimage provides the io module to perform input and output operations on images. For the convenience of practice, a data module is also provided, which contains some sample images, which we can use directly.

Import skimage module is available:

from skimage import io

1. Read the image from the outside and display it

Use the skimage.io.imread(fname) function with a parameter indicating the path of the file to be read. To display an image, use the skimage.io.imshow(arr) function with a parameter indicating the arr array to be displayed (the read image is calculated in the form of a numpy array). example:

from skimage import io
img=io.imread('D:/lena.bmp')
io.imshow(img)

2. The program comes with images

The skimage program comes with some sample images. If we don't want to read images from outside, we can use these sample images directly:

Astronaut astronaut image
coffee cup of coffee image
camera person holding camera image
coins coin image
moon moon image
checkerboard checkerboard image
horse horse image
page book page image
chelsea kitten image
hubble_deep_field starry sky image
text text image
clock clock image

To display these images, the following code can be used without any parameters

from skimage import io,data
img=data.coffee()
io.imshow(img)

The image name corresponds to the function name. For example, the function name corresponding to the coffee image is coffee(). These sample images are stored under the skimage installation directory, and the path name is data_dir. We can print this path to see:

from skimage import data_dir
print(data_dir)

show:
aaa

In other words, the following two lines of code to read an image have the same effect:

from skimage import data_dir,data,io
img1=data.coffee() 
img2=io.imread(data_dir+'/coffee.png')  

3. Save the image

Use the imsave(fname, arr) function of the io module to achieve. The first parameter indicates the saved path and name, and the second parameter indicates the array variable to be saved. example:

from skimage import io,data
img=data.chelsea()
io.imshow(img)
io.imsave('d:/cat.jpg',img)

While saving the image, it also plays the role of converting the format. If the image format is a jpg image when read and saved as a png format, the image is converted from a jpg image to a png image and saved.

4. Image information

如果想知道图像信息,可以直接打印输出,代码如下:
from skimage import io,data
img=data.chelsea()
io.imshow(img)
print(type(img))  #显示类型
print(img.shape)  #显示尺寸
print(img.shape[0])  #图像宽度
print(img.shape[1])  #图像高度
print(img.shape[2])  #图像通道数
print(img.size)   #显示总像素个数
print(img.max())  #最大像素值
print(img.min())  #最小像素值
print(img.mean()) #像素平均值

5. Image drawing

matplotlib is a professional drawing library, you can set multiple figure windows, set the title of the figure, hide the coordinate ruler, and even use subplot to display multiple images in a figure. Generally, we can import the matplotlib library like this:
import matplotlib.pyplot as plt
That is to say, we actually use the pyplot module of the matplotlib package for drawing. In fact, we have already used image drawing before, such as:

io.imshow(img)  

The essence of this line of code is to use the matplotlib package to draw the image, and return a matplotlib type of data after the drawing is successful. Therefore, we can also write:

import matplotlib.pyplot as plt
plt.imshow(img)

The imshow() function format is:
matplotlib.pyplot.imshow(X, cmap=None)
X: The image or array to be drawn.
cmap: color map (colormap), drawn in RGB(A) color space by default.
Other optional color maps are as follows:

color spectrum describe
autumn red-orange-yellow
bone black-white, x-ray
cool Cyan-Magenta
copper black-copper
flag red-white-blue-black
gray black-white
hot black-red-yellow-white
hsv HSV color space, red-yellow-green-cyan-blue-magenta-red
inferno black-red-yellow
jet blue-cyan-yellow-red
magma black-red-white
pink black-pink-white
plasma green-red-yellow
prism Red-yellow-green-blue-purple-…-green mode
spring magenta-yellow
summer green-yellow
viridis blue-green-yellow
winter blue-green

Gray, jet, etc. are widely used, such as:

plt.imshow(image,plt.cm.gray)
plt.imshow(img,cmap=plt.cm.jet)

After drawing the picture on the window, return an AxesImage object. To display this object on the window, we can call the show() function to display it.

from skimage import io,data
img=data.astronaut()
dst=io.imshow(img)
print(type(dst))
io.show()

To display an image, we can also write:

import matplotlib.pyplot as plt
from skimage import io,data
img=data.astronaut()
plt.imshow(img)
plt.show()

Methods for creating windows and dividing subgraphs:

1. Use the figure function and subplot function to create the main window and subplot respectively

Example: Separate and display three channels of astronaut images simultaneously

from skimage import data
import matplotlib.pyplot as plt
img=data.astronaut()
plt.figure(num='astronaut',figsize=(8,8))  #创建一个名为astronaut的窗口,并设置大小 
plt.subplot(4,1,1)     #将窗口分为两行两列四个子图,则可显示四幅图像
plt.title('origin image')   #第一幅图像标题
plt.imshow(img)      #绘制第一幅图像

plt.subplot(4,1,2)     #第二个子图
plt.title('R channel')   #第二幅图像标题
plt.imshow(img[:,:,0],plt.cm.gray)      #绘制第二幅图像,且为灰度图
plt.axis('off')     #不显示坐标尺寸

plt.subplot(4,1,3)     #第三个子图
plt.title('G channel')   #第三幅图像标题
plt.imshow(img[:,:,1],plt.cm.gray)      #绘制第三幅图像,且为灰度图
plt.axis('off')     #不显示坐标尺寸

plt.subplot(4,1,4)     #第四个子图
plt.title('B channel')   #第四幅图像标题
plt.imshow(img[:,:,2],plt.cm.gray)      #绘制第四幅图像,且为灰度图
plt.axis('on')     #显示坐标尺寸

plt.show()   #显示窗口

In the image drawing process, we use the figure() function under the matplotlib.pyplot module to create a display window. The format of this function is:

matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None)

All parameters are optional and have default values, so this function can be called without any parameters, among them:
num: either integer or character type. If set to an integer, the integer number represents the serial number of the window. If set to String, the string represents the name of the window. Use this parameter to name the window. If two windows have the same serial number or name, the latter window will cover the former one.

figsize: Set the window size. It is a tuple-type integer, such as figsize=(8, 8)
dpi: Integer number, indicating the resolution of the window.
facecolor: The background color of the window.
edgecolor: The border color of the window.
The window created by the figure() function can only display one image. If you want to display multiple images, you need to divide the window into several sub-figures and display different images in each sub-figure. We can use the subplot() function to divide the subplot, the function format is:
matplotlib.pyplot.subplot(nrows, ncols, plot_number)
nrows: the number of rows of the subplot.
ncols: The number of columns of the subplot.
plot_number: The number of the current subplot.
like:

plt.subplot(2,2,1)#则表示将figure窗口划分成了2行2列共4个子图,当前为第1个子图。我们有时也可以用这种写法:
plt.subplot(221)#两种写法效果是一样的。
#每个子图的标题可用title()函数来设置,是否使用坐标尺可用axis()函数来设置,如:
plt.subplot(221)
plt.title("first subwindow")
plt.axis('off')   

2. Use subplots to create display windows and divide subgraphs

There is another writing method that can also divide subgraphs, for example:

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

img = data.coffee()

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
ax0, ax1, ax2, ax3 = axes.ravel()

ax0.imshow(img)
ax0.set_title('Origin image')

ax1.imshow(img[:, :, 0], cmap=plt.cm.gray)
ax1.set_title('R channel')

ax2.imshow(img[:, :, 1], cmap=plt.cm.gray)
ax2.set_title('G channel')

ax3.imshow(img[:, :, 2], cmap=plt.cm.gray)
ax3.set_title('B channel')

for ax in axes.ravel():
    ax.axis('off')

fig.tight_layout()  #自动调整subplot间的参数

Use the subplots() function directly to create and divide windows. Note that there is one more s than the previous subplot() function, and the format of this function is:

matplotlib.pyplot.subplots(nrows=1, ncols=1)
nrows: The number of all subplot rows, the default is 1.
ncols: number of columns in all subplots, defaults to 1.

Return a window figure, and a tuple-type ax object, which contains all subfigures, which can be combined with the ravel() function to list all subfigures, such as:

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
ax0, ax1, ax2, ax3 = axes.ravel()
# 创建了2行2列4个子图,分别取名为ax0,ax1,ax2和ax3, 每个子图的标题用set_title()函数来设置,如:
ax0.imshow(img)
ax0.set_title("Original image")
# 如果有多个子图,我们还可以使用tight_layout()函数来调整显示的布局,该函数格式为:
matplotlib.pyplot.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)
# 所有的参数都是可选的,调用该函数时可省略所有的参数。
pad: 主窗口边缘和子图边缘间的间距,默认为1.08
h_pad, w_pad: 子图边缘之间的间距,默认为 pad
rect: 一个矩形区域,如果设置这个值,则将所有的子图调整到这个矩形区域内。
# 一般调用为:
plt.tight_layout()  #自动调整subplot间的参数

To sum up, the functions commonly used to draw and display images are:

Function name Function calling format
figure Create a display window plt.figure(num=1,figsize=(8,8)
imshow draw image plt.imshow(image)
show display window plt.show()
subplot Partition subgraph plt.subplot(2,2,1)
title Set the subplot title (used in conjunction with subplot) plt.title(‘origin image’)
axis Whether to display the coordinate ruler plt.axis(‘off’)
subplots Create a window with multiple subplots fig,axes=plt.subplots(2,2,figsize=(8,8))
ravel set variables for each subplot ax0,ax1,ax2,ax3=axes.ravel()
set_title Set the subplot title (used in conjunction with axes) ax0.set_title(‘first window’)
tight_layout Automatically adjust subplot display layout plt.tight_layout()

Guess you like

Origin blog.csdn.net/weixin_52051554/article/details/127358856