绘制图像轮廓:
img = cv2.imread("image.png")
# 彩色图像转为变成单通道灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 灰度图像转为二值图像
t, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 检测图像中出现的所有轮廓,记录轮廓的每一个点
contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
# 绘制所有轮廓,宽度为5,颜色为红色
cv2.drawContours(img, contours, -1, (0, 0, 255), 5)
为轮廓添加矩形框:
# 获取第一个轮廓的最小矩形边框,记录坐标和宽高
x, y, w, h = cv2.boundingRect(contours[0])
# 绘制红色矩形
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
为轮廓添加圆形框:
contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# 获取最小圆形边框的圆心点和半径
center, radius = cv2.minEnclosingCircle(contours[0])
# 圆心点横坐标转为近似整数
x = int(round(center[0]))
# 圆心点纵坐标转为近似整数
y = int(round(center[1]))
cv2.circle(img, (x, y), int(radius), (0, 0, 255), 2)
Canny边缘检测:
img = cv2.imread("image.png")
r1 = cv2.Canny(img, 10, 50)
直线检测:
img = cv2.imread("image.jpg")
# 复制原图
o = img.copy()
# 使用中值滤波进行降噪
o = cv2.medianBlur(o, 5)
gray = cv2.cvtColor(o, cv2.COLOR_BGR2GRAY)
binary = cv2.Canny(o, 50, 150) # 绘制边缘图像
# 检测直线,精度为1,全角度,阈值为15,线段最短100,最小间隔为18
lines = cv2.HoughLinesP(binary, 1, np.pi / 180, 15, minLineLength=100, maxLineGap=18)
for line in lines: # 遍历所有直线
x1, y1, x2, y2 = line[0] # 读取直线两个端点的坐标
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2) # 在原始图像上绘制直线
圆环检测:
img = cv2.imread("image.jpg")
o = img.copy()
o = cv2.medianBlur(o, 5)
gray = cv2.cvtColor(o, cv2.COLOR_BGR2GRAY) # 从彩色图像变成单通道灰度图像
# 检测圆环,圆心最小间距为70,Canny最大阈值为100,投票数超过25。最小半径为10,最大半径为50
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 70, param1=100, param2=25, minRadius=10, maxRadius=50)
circles = np.uint(np.around(circles)) # 将数组元素四舍五入成整数
for c in circles[0]: # 遍历圆环结果
x, y, r = c # 圆心横坐标、纵坐标和圆半径
# 绘制圆环
cv2.circle(img, (x, y), r, (0, 0, 255), 3)
# 绘制圆心
cv2.circle(img, (x, y), 2, (0, 0, 255), 3)