【Python】scikit-image的measure,morphology,io,filters等

Foreword:

There are still many python-based image processing packages, such as PIL, Pillow, opencv, scikit-image, etc. Among them, PIL and Pillow only provide the most basic digital image processing with limited functions; opencv is essentially a C++ library, but provides a python interface, the official update speed is very slow, and the installation is very difficult. On the whole, scikit-image is an image processing package based on scipy. It has complete functions. At the same time, it processes pictures as numpy arrays. It integrates almost all the image processing functions of matlab, in terms of data processing methods, function names, etc. The imitating posture of matlab is very good.

More importantly, as an image processing package of python, this package is completely open source and free, and it can rely on the powerful functions of python to work with tensorflow and other software in mainstream deep learning and other fields. Therefore, using scikit-image for image processing is a very good choice. Matlab can do everything that matlab can do, and he can do things that matlab can’t do. I personally think that in the field of digital image processing, it can completely replace matlab. The matlab, which is expensive and the interface is not very beautiful, is almost crying in the toilet.

Of course, if you have a certain programming foundation, the best way to learn this package is to read the official document, the official scikit-image document . For beginners, you can read the introduction of the popular version first.

1. Installation.

This package will report an error when installed using pip. Offline installation is recommended. For specific installation methods, see: How to install cv2 and skimage (scikit-image) modules under python3 under windows

Two, import the scikit-image package

This package has a lot of sub-modules, which are responsible for different functions. Therefore, when importing, different modules can be imported for different functions. The functions of each module are as follows:

Submodule name Main function
I Read, save and display pictures or videos
data Provide some test pictures and sample data
color Color space transformation
filters Image enhancement, edge detection, sorting filter, automatic threshold, etc.
draw Basic graphics drawing operations on numpy arrays, including lines, rectangles, circles, text, etc.
transform Geometric transformation or other transformations, such as rotation, stretching and Radon transformation, etc.
morphology Morphological operations, such as opening and closing operations, skeleton extraction, etc.
exposure Picture intensity adjustment, such as brightness adjustment, histogram equalization, etc.
feature Feature detection and extraction, etc.
measure Measurement of image attributes, such as similarity or contour
segmentation Image segmentation
restoration Image restoration
useful General function

Described below separately

from skimage import 函数名

1. Read and display the image. (Module used: io)

from skimage import io
img=io.imread('图片路径',as_grey = bool值)
io.imshow(img)

Among them, if the as_grey attribute is True, it will be automatically converted into a grayscale image after reading the color image. Otherwise, the color image will be read, and the default is False. 
After reading the picture, you can get various attributes of the picture

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()) #像素平均值

2. Save the image

The syntax of matlab is almost the same when reading. When writing a picture file, just imwrite()change the imsave()function in matlab to a function .

from skimage import io,data
img=io.imread('图片路径',as_grey = bool值)#以上的读取图片函数
io.imshow(img)
io.imsave('保存路径',img)

When saving pictures, you can also save them in different formats (jpg, png, etc.).

For a binary image, io.imsave()directly saving with a function will result in a black image. I personally think it is because the program still thinks that the value range of the image is 0~255 when saving. It is necessary to convert the data type. It is more convenient to know The solution can be exchanged in the comment area

3. Image cropping and scaling. (Module used: transform)

1) Change the picture size resize

Similarly, a skimage.transform.resize(image, output_shape)function is provided, which is no different from the syntax for resizing an image in matlab.

image: The image that needs to be resized

output_shape: new image size

from skimage import transform,io
import matplotlib.pyplot as plt#用于显示图像
img=io.imread('图片路径',as_grey = bool值)
dst=transform.resize(img, (长, 宽))
plt.figure('resize')
plt.subplot(121)
plt.title('before resize')
plt.imshow(img,plt.cm.gray)
plt.subplot(122)
plt.title('before resize')
plt.imshow(dst,plt.cm.gray)
plt.show()

The picture can be changed into 80*60 size.

4. Marking and selection of connected domains of pictures (module used: measure)

1) Get connected domain and its attributes

Obtaining the connected domain of an image is a relatively advanced function in image processing. Matlab can directly obtain the connected domain of an image through a function. In the skimage package, we can also use the label() function under the measure submodule to achieve the same effect.

Function format:

from skimage import measure
labels = measure.label(二值图像,connectivity=None)
  • Connectivity represents the mode of connection, 1 represents 4 adjacent, 2 represents 8 adjacent.

Returns an array of the same size as the image, the background is 0, and the connected domain of the foreground is marked from 1 upwards.

Of course, what we do at this time is to mark the connected regions for people to see. If you want to operate on each connected region separately, such as calculating area, circumscribed rectangle, convex hull area, etc., you need to call the regionprops() of the measure submodule. function. After importing the measure package as above, the function format is: In 
label_att = measure.regionprops(label_image) 
this way, we can get the attributes of any connected domain in the image from the "label_att" array. The attribute list is as follows:

Attribute name Types of description
area int Total number of pixels in the area
bbox tuple Bounding box (min_row, min_col, max_row, max_col)
centroid array Center of mass coordinates
convex_area int The total number of pixels in the convex hull
convex_image ndarray Convex hull of the same size as the bounding box
coords ndarray Pixel coordinates in the area
Eccentricity float Eccentricity
equivalent_diameter float The diameter of a circle with the same area as the area
euler_number int Regional Euler number
extent float The ratio of the area area to the area of ​​the bounding box
filled_area int The total number of pixels filled between the area and the bounding box
perimeter float Area circumference
label int Area marker

It should be noted here that the connected domain background obtained by the measure.label function is 0, the connected domain of the foreground is actually calculated from 1, while the connected domain obtained by the measure.regionprops function does not contain the background, and the connected domain attribute of the foreground is from 0 Started.  
Here is an example: 
just find a picture as follows: 
Test picture (color picture) 
Run the code as follows:

from skimage import io,filters,measure 
img = io.imread('test.jpg',as_grey=True) #读取图片
thresh = filters.threshold_otsu(img)  #用otsu算法确定最佳分割阈值
bwimg =(img>=(thresh))  #用阈值进行分割,生成二值图像
labels = measure.label(bwimg)  #标记连通域
label_att = measure.regionprops(labels) #获取各个连通域的属性。

labels value
label_att value

It can be seen that labels have found 5 connected domains, while label_att has only four connected domain attributes. This is because the background connected domain attributes are not included.

2) Delete small areas

The picture will inevitably have noise. When the connected domain is processed above, the noise will be counted as a small connected domain. The remove_small_objects() function of the morphology sub-module provides a convenient noise removal function. Function format (usually used in conjunction with the previous function):

from skimage import morphology
img1 = morphology.remove_small_objects(ar, min_size=要删除的连通域大小阈值, connectivity=1,in_place=False)

img1 is a binary image that is smaller than the threshold of the connected domain area is deleted. 
Among them, the meaning of each parameter is as follows:

  • ar: The array of labeled connected domains obtained above (only binary images)
  • connectivity: adjacency mode, 1 means 4 adjacency, 2 means 8 adjacency
  • in_place: bool type value, if it is True, it means to delete a small area in the input image directly, otherwise delete it after copying. The default is False.

appendix:

The scikit-image package imitates matlab even in many details. For example, matlab will bring some pictures for users to test. If we don’t want to read pictures from outside, we can directly use these sample pictures to perform functions Test, the scikit-image package also has the following functions: 
and the method of use is also very simple:

from skimage import io,data
img=data.lena()
io.imshow(img)
astronaut Astronaut pictures
coffee A cup of coffee pictures
lena lena beauty pictures
camera Picture of a person holding a camera
coins Coin picture
moon Moon pictures
checkerboard Chessboard picture
horse Horse pictures
page Book page pictures
chelsea Kitten pictures
hubble_deep_field Starry sky picture
text Text picture
clock Clock pictures
immunohistochemistry Colon picture

The image name corresponds to the function name. These sample images are stored in the installation directory of skimage, and the path name is data_dir. You can also print this path:

from skimage import data_dir
print(data_dir)

Reference materials:

1.  Python digital image processing (18): Advanced morphological processing 

2.  Python skimage image processing (1) There are some image cropping related content

Guess you like

Origin blog.csdn.net/u013066730/article/details/108341864