---
title: "数学形态学"
author: "cakin24"
date: "2017-08-05T07:46:50Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2017-08-05T07:46:50Z"
id: 2388395
url: "https://cakin24.iteye.com/blog/2388395"
---

**一 原始随机图像**

1、代码

1. `import numpy as np`
2. `import matplotlib.pyplot as plt`
3. `square = np.zeros((32,32))#全0数组`
4. `square[10:20,10:20]=1#把其中一部分设置为1`
5. `x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置`
6. `square[x,y]=1#把随机位置设置为1`
7. `plt.imshow(square)#原始随机图像`
8. `plt.show()`

2、运行结果

![](http://dl2.iteye.com/upload/attachment/0126/4191/ee31a617-f6ec-33d5-887d-3a5c9b0831e5.png)  
 

 

**二 开运算**

1、代码

01. `import numpy as np`
02. `import matplotlib.pyplot as plt`
03. `from scipy import ndimage`
04. `square = np.zeros((32,32))#全0数组`
05. `square[10:20,10:20]=1#把其中一部分设置为1`
06. `x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置`
07. `square[x,y]=1#把随机位置设置为1`
08. `open_square = ndimage.binary_opening(square)#开运算`
09. `plt.imshow(open_square)`
10. `plt.show()`

2、运行结果

![](http://dl2.iteye.com/upload/attachment/0126/4193/04b8ed20-2b68-3d10-bbe6-a25d98f9e922.png)  
 

 

**三 膨胀运算**

1、代码

01. `import numpy as np`
02. `import matplotlib.pyplot as plt`
03. `from scipy import ndimage`
04. `square = np.zeros((32,32))#全0数组`
05. `square[10:20,10:20]=1#把其中一部分设置为1`
06. `x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置`
07. `square[x,y]=1#把随机位置设置为1`
08. `eroded_square = ndimage.binary_erosion(square)#膨胀运算`
09. `plt.imshow(eroded_square)`
10. `plt.show()`

2、运行结果

![](http://dl2.iteye.com/upload/attachment/0126/4195/85044b41-be32-3b68-9e07-f1867d806f4a.png)  
 

 

**四 闭运算**

1、代码

01. `import numpy as np`
02. `import matplotlib.pyplot as plt`
03. `from scipy import ndimage`
04. `square = np.zeros((32,32))#全0数组`
05. `square[10:20,10:20]=1#把其中一部分设置为1`
06. `x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置`
07. `square[x,y]=1#把随机位置设置为1`
08. `closed_square = ndimage.binary_closing(square)#闭运算`
09. `plt.imshow(closed_square)`
10. `plt.show()`

2、运行结果

![](http://dl2.iteye.com/upload/attachment/0126/4197/c5479c91-633e-3c88-b371-fa717658af1b.png)