import matplotlib.pyplot as plt
fig = plt.figure()
# fig, axes = plt.subplots(nrows=2, ncols=2)
ax1 = fig.add_subplot(3, 5, 1)
# ax1 = plt.subplot(3, 5, 1)
ax2 = plt.subplot(3, 5, 2)
ax3 = plt.subplot(3, 5, 3)
ax4 = plt.subplot(3, 5, 4)
ax5 = plt.subplot(3, 5, 5)
ax6 = plt.subplot(3, 5, 6)
ax7 = plt.subplot(3, 5, 7)
ax8 = plt.subplot(3, 5, 8)
path='./img/0.jpg'#路径二维码
path = './img/sachin.jpg' # 路径
plt.sca(ax1)
# img = cv2.imread(path, flags=1)#原色
img = cv2.imread(path, flags=0)#灰色
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # plt以RGB格式读取数组,而CV2是以BGR模式读取,所以需要转化
img = cv2.cvtColor(img, 1) # plt以RGB格式读取数组,而CV2是以BGR模式读取,所以需要转化
# img=255-img
plt.title('二维码') # 图像标题
plt.axis('off')
plt.imshow(img)
#
plt.sca(ax2)
blur = cv2.blur(img, (5, 5))
plt.title('blur') # 图像标题
plt.imshow(blur)
#
plt.sca(ax3)
gau_blur = cv2.GaussianBlur(img, (5, 5), 0)
plt.title('gau_blur') # 图像标题
plt.imshow(gau_blur)
#
plt.sca(ax4)
median = cv2.medianBlur(img, 5)
plt.title('median') # 图像标题
plt.imshow(median)
#
plt.sca(ax5)
bi_blur = cv2.bilateralFilter(img, 9, 75, 75)
plt.title('bi_blur') # 图像标题
plt.imshow(bi_blur)
#
kernel = np.ones((3, 3), dtype=np.uint8)
res = cv2.resize(img, None, fx=0.6, fy=0.6,
interpolation=cv2.INTER_CUBIC) # 图形太大了缩小一点
B, G, R = cv2.split(res) # 获取红色通道
# img = R
_, RedThresh = cv2.threshold(img, 160, 255, cv2.THRESH_BINARY)
# OpenCV定义的结构矩形元素
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
eroded = cv2.erode(RedThresh, kernel) # 腐蚀图像
dilated = cv2.dilate(RedThresh, kernel) # 膨胀图像
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 定义矩形结构元素
closed1 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel, iterations=1) # 闭运算1
closed2 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel, iterations=3) # 闭运算2
opened1 = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel, iterations=1) # 开运算1
opened2 = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel, iterations=3) # 开运算2
gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel) # 梯度
TOPHAT_img = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) # 顶帽运算
BLACKHAT_img = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) # 黒帽运算
#边缘检测
absdiff_img = cv2.absdiff(dilated, eroded);
retval, threshold_img = cv2.threshold(absdiff_img, 40, 255, cv2.THRESH_BINARY);
bitwise = cv2.bitwise_not(threshold_img);
plt.sca(ax6)
plt.title('eroded') # 图像标题
plt.imshow(eroded)
plt.sca(ax7)
plt.title('dilated') # 图像标题
plt.imshow(dilated)
plt.sca(plt.subplot(3, 5, 8))
plt.title('closed1') # 图像标题
plt.imshow(closed1)
plt.sca(plt.subplot(3, 5, 9))
plt.title('closed2') # 图像标题
plt.imshow(closed2)
plt.sca(plt.subplot(3, 5, 10))
plt.title('opened1') # 图像标题
plt.imshow(opened1)
plt.subplot(3, 5, 11)
plt.title('opened2') # 图像标题
plt.imshow(opened2)
plt.subplot(3, 5, 12)
plt.title('gradient') # 图像标题
plt.imshow(gradient)
plt.subplot(3, 5, 13)
plt.title('TOPHAT_img') # 图像标题
plt.imshow(TOPHAT_img)
plt.subplot(3, 5, 14)
plt.title('BLACKHAT_img') # 图像标题
plt.imshow(BLACKHAT_img)
plt.subplot(3, 5, 15)
plt.title('bitwise') # 图像标题
plt.imshow(bitwise)
plt.show()