# 使用函数matplotlib.pyplot.imshow()以不同的参数形式显示灰度图像。
import cv2
import numpy as np
import matplotlib.pyplot as plt
o = cv2.imread('D:\\401.bmp')
g=cv2.cvtColor(o, cv2.COLOR_BGR2GRAY)
#ret, img = cv2.threshold(g, 127, 255, cv2.THRESH_TRUNC)
ret, img = cv2.threshold(g, 50, 255, cv2.THRESH_BINARY)
kernel = np.ones((10, 10), np.uint8)
img_dilate = cv2.dilate(img, kernel, iterations = 1)
cv2.imwrite('D:\\img_dilate.bmp', img_dilate)
# Creating kernel
kernel = np.ones((10, 10), np.uint8)
# Using cv2.erode() method
image = cv2.erode(img_dilate, kernel)
cv2.imwrite('D:\\erode.bmp', image)
#key = cv2.waitKey(0) # 等待按键命令, 1000ms 后自动关闭
# Saving the image
contours,cnts=cv2.findContours(image,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#cv2.imshow('lunkuo',image2)
cv2.drawContours(o, contours, -1, (0,0,255),3)
cv2.imwrite('D:\\lunkuo.bmp', o)
print(np.size(cnts))
#以下为只绘制轮廓
# 复制原图
img1 = o.copy()
# 创建一幅相同大小的白色图像
img2 = np.ones(o.shape)
contours2 = sorted(contours, key=lambda a: cv2.contourArea(a), reverse=True)
for c in contours2:
area = cv2.contourArea(c)
print(area)
# 只输出面积大于500轮廓
if area<500:break
# 分别在复制的图像上和白色图像上绘制当前轮廓
cv2.drawContours(img1, [c],0, (0,255,0), 3)
cv2.drawContours(img2, [c],0, (0,255,0), 3)
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
print("坐标x1,坐标y1,坐标x2,坐标y2,坐标x3,坐标y3,坐标x4,坐标y4",box[0, 0],box[0, 1],box[1, 0],box[1, 1],box[2, 0],box[2, 1],box[3, 0],box[3, 1])
print(rect)
#plot_images(1,3,[img,img1,img2], gray=True)
cv2.imwrite('D:\\img1.bmp', img1)
cv2.imwrite('D:\\img2.bmp', img2)
#cnt = np.array([[x1,y1],[x2,y2],[x3,y3],[x4,y4]]) # 必须是array数组的形式
#rect = cv2.minAreaRect(Coutous[0]) # 得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度)
#box = np.int0(cv2.boxPoints(rect)) #通过box会出矩形框
#print(np.size(cnts))
plt.figure("灰度图像显示演示")
plt.subplot(221); plt.imshow(o, cmap=plt.cm.gray)
plt.subplot(222); plt.imshow(g, cmap=plt.cm.gray_r)
plt.subplot(223); plt.imshow(img_dilate, cmap='gray');plt.savefig("erode.png",dpi=300)
plt.subplot(224); plt.imshow(image, cmap='gray');plt.savefig("dilate.png",dpi=300)
#plt.subplot(321); plt.imshow(image, cmap='gray')
运行结果