#4、边缘膨胀. getStructuringElement:获取结构化元素
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # 椭圆结构
# kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) # 十字结构
# kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 矩形结构
dilate = cv2.dilate(blurred,cv2.getStructuringElement(cv2.MORPH_RECT,(3,3)))
#5、canny:边缘检测
edged = cv2.Canny(dilate,30,120,3)
#6、findContours:轮廓检测
#cv2.findContours()函数返回两个值,一个是轮廓本身,还有一个是每条轮廓对应的属性
#cnts[0]是图中所有的轮廓
cnts = cv2.findContours(edged.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]
docCnt = None
#如果轮廓的个数是大于0的就打印出所有的轮廓
if len(cnts) > 0:
# 根据轮廓面积从大到小排序:所求轮廓面积较大,提升运算速度
cnts = sorted(cnts,key=cv2.contourArea,reverse=True)
#按照轮廓面积从大到小,打印出所有的轮廓
for c in cnts:
# cv.approxPolyDP() 的参数1是源图像的某个轮廓;参数2(epsilon)是一个距离值,
# 表示多边形的轮廓接近实际轮廓的程度,值越小,越精确;参数3表示是否闭合
approx = cv2.approxPolyDP(c, 123, True)
# 轮廓为4个点表示找到纸张
if len(approx) == 4:
docCnt = approx
break
#在原图上
#分别打印出4个顶点
#分别以每个点为圆心,10为半径,(255, 0, 0)为颜色,画圆圈
for peak in docCnt:
peak = peak[0]
cv2.circle(img, tuple(peak), 10, (0, 0, 255))
#绘图:调试过程中看图片处理成什么样的
plt.figure()
plt.imshow(img.astype(np.uint8), cmap='gray')