# -*- coding:utf-8 -*-
import cv2
import numpy as np
'''
步骤:
(1).彩色图像转换为灰度图像(以灰度图或者单通道图读入)
(2).对图像进行高斯模糊(去噪)
(3).计算图像梯度,根据梯度计算图像边缘幅值与角度
(4).沿梯度方向进行非极大值抑制(边缘细化)
(5).双阈值边缘连接处理
(6).二值化图像输出结果
'''
cv2.namedWindow('Cannys', 0)
# 创建滑动条
cv2.createTrackbar('minval', 'Cannys', 120, 300, lambda x: None)
cv2.createTrackbar('maxval', 'Cannys', 200, 300, lambda x: None)
cv2.createTrackbar('blur', 'Cannys', 12, 100, lambda x: None)
# 绘制等高线轮廓
def draw_Contour_Line(frame):
# 去噪
blur = cv2.getTrackbarPos('blur', 'Cannys')
frame = cv2.GaussianBlur(frame, (5, 5), blur * 0.1)
# 读取滑动条数值
minval = cv2.getTrackbarPos('minval', 'Cannys')
maxval = cv2.getTrackbarPos('maxval', 'Cannys')
# threshold1 threshold2 两个阈值,小的控制边缘连接,大的控制强边缘的初始分割。如果一个像素的梯度大于上限值,则认为是边缘像素,如果小于下限阈值,则抛弃,如若点的梯度在两者之间,则当这个点与高于上限值的像素点连接时才保留,否则删除。
# aperture_size 算子内核大小,表示Sobel 算子大小,默认为3即表示一个3*3的矩阵
canny = cv2.Canny(frame, threshold1=minval, threshold2=maxval)
# canny = cv2.Canny(frame, threshold1=60, threshold2=180)
# RETR_EXTERNAL:表示只检测最外层轮廓; RETR_CCOMP:提取所有轮廓; RETR_TREE:提取所有轮廓并重新建立网状轮廓结构
# CHAIN_APPROX_SIMPLE:压缩水平方向,垂直方向,对角线方向的元素,值保留该方向的重点坐标; CHAIN_APPROX_NONE:获取每个轮廓的每个像素,相邻的两个点的像素位置差不超过1
contours, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
frameProcessed = np.zeros(frame.shape, dtype=np.uint8)
frameProcessed = cv2.cvtColor(frameProcessed, cv2.COLOR_GRAY2BGR)
cv2.drawContours(frameProcessed, contours, -1, color=(255, 0, 0), thickness=2) # blue
return frameProcessed
def draw_Contour_Line2(frame):
frame = cv2.GaussianBlur(frame, (5, 5), 1.5)
minval = cv2.getTrackbarPos('minval', 'Cannys')
maxval = cv2.getTrackbarPos('maxval', 'Cannys')
canny = cv2.Canny(frame, threshold1=minval, threshold2=maxval)
# canny = cv2.Canny(frame, 60, 180)
return canny
def draw_Contour_Line3(frame):
frame = cv2.GaussianBlur(frame, (5, 5), 1.5)
canny = cv2.Canny(frame, threshold1=60, threshold2=180)
# 形态学:边缘检测
_, Thr_img = cv2.threshold(canny, 210, 255, cv2.THRESH_BINARY) # 设定红色通道阈值210(阈值影响梯度运算效果)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 定义矩形结构元素
gradient = cv2.morphologyEx(Thr_img, cv2.MORPH_GRADIENT, kernel) # 梯度
return gradient
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
gray_L = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame_edge1 = draw_Contour_Line(gray_L)
frame_edge2 = draw_Contour_Line2(gray_L)
frame_edge3 = draw_Contour_Line3(gray_L)
cv2.imshow("frame", frame)
cv2.imshow("Canny-contour1", frame_edge1)
cv2.imshow("Canny-contour2", frame_edge2)
cv2.imshow("Canny-contour3", frame_edge3)
if cv2.waitKey(1) == ord("q"):
break
camera.release()
cv2.destroyAllWindows()
04-29
1214
08-26
4925
12-03
432