一 原始随机图像
1、代码
import numpy as np
import matplotlib.pyplot as plt
square = np.zeros((32,32))#全0数组
square[10:20,10:20]=1#把其中一部分设置为1
x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置
square[x,y]=1#把随机位置设置为1
plt.imshow(square)#原始随机图像
plt.show()
2、运行结果
![](https://i-blog.csdnimg.cn/blog_migrate/be7e843f6121b0cd6b3bd1d238335b8b.png)
二 开运算
1、代码
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
square = np.zeros((32,32))#全0数组
square[10:20,10:20]=1#把其中一部分设置为1
x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置
square[x,y]=1#把随机位置设置为1
open_square = ndimage.binary_opening(square)#开运算
plt.imshow(open_square)
plt.show()
2、运行结果
![](https://i-blog.csdnimg.cn/blog_migrate/04f22bb8d8b94b3aeea50479ac45f1db.png)
三 膨胀运算
1、代码
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
square = np.zeros((32,32))#全0数组
square[10:20,10:20]=1#把其中一部分设置为1
x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置
square[x,y]=1#把随机位置设置为1
eroded_square = ndimage.binary_erosion(square)#膨胀运算
plt.imshow(eroded_square)
plt.show()
2、运行结果
![](https://i-blog.csdnimg.cn/blog_migrate/fe402144ae1ab467d0d7e42661630202.png)
四 闭运算
1、代码
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
square = np.zeros((32,32))#全0数组
square[10:20,10:20]=1#把其中一部分设置为1
x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置
square[x,y]=1#把随机位置设置为1
closed_square = ndimage.binary_closing(square)#闭运算
plt.imshow(closed_square)
plt.show()
2、运行结果
![](https://i-blog.csdnimg.cn/blog_migrate/5b2d0fedd3dc2dc8423a69fce34b1456.png)