1、检测所有轮廓,用不同颜色画出
import cv2
import numpy as np
# 读取图像
image_path = r"C:\Users\yh\Pictures\1.png"
img = cv2.imread(image_path)
# 图像灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化图像
_, thresholded = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY)
# 轮廓检测
contours, _ = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 在原图上画出轮廓
for i, contour in enumerate(contours):
# 选择不同颜色进行绘制
color = (0, 0, 255) if i % 2 == 0 else (0, 255, 0)
cv2.drawContours(img, [contour], -1, color, 2)
# 显示标注后的图像
cv2.imshow("Contours", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
![](https://i-blog.csdnimg.cn/blog_migrate/f9c56a3fe3bec4e37885118aabe30f6a.png)
2、对其中一段轮廓进行角点检测
import cv2
import numpy as np
# 读取图像
image_path = r"C:\Users\yh\Pictures\1.png"
img = cv2.imread(image_path)
# 图像灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化图像
_, thresholded = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY)
# 轮廓检测
contours, _ = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 选择第一个轮廓进行角点检测
contour = contours[1]
# 创建空白的二值图像
mask = np.zeros_like(gray)
# 将轮廓绘制在空白图像上
cv2.drawContours(mask, [contour], -1, 255, thickness=cv2.FILLED)
# 角点检测
corners = cv2.goodFeaturesToTrack(mask, maxCorners=10, qualityLevel=0.1, minDistance=10)
# 标注角点
if corners is not None:
corners = np.int0(corners)
for corner in corners:
x, y = corner.ravel()
cv2.circle(img, (x, y), 3, (255, 0, 0), -1)
# 显示标注后的图像
cv2.imshow("Corner Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
![](https://i-blog.csdnimg.cn/blog_migrate/eafcd60883fe3e36170362e70bacb4be.png)
![](https://i-blog.csdnimg.cn/blog_migrate/60ac04f4da4f37ccb70f502e9a8c48bd.png)
3、坐标变换到右下角角点
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 读取图像
image_path = r"C:\Users\yh\Pictures\1.png"
img = cv2.imread(image_path)
# 图像灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化图像
_, thresholded = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY)
# 轮廓检测
contours, _ = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 选择第三个轮廓进行处理
contour = contours[2]
# 找到右下角的角点
bottom_right_corner = None
max_x, max_y = 0, 0
for point in contour:
x, y = point.ravel()
if x >= max_x and y >= max_y:
max_x = x
max_y = y
bottom_right_corner = (x, y)
# 建立新坐标系并转换轮廓点
transformed_contour = []
for point in contour:
x, y = point.ravel()
offset_x = -y + bottom_right_corner[1]
offset_y = x - bottom_right_corner[0]
transformed_contour.append((offset_x, offset_y))
# 绘制轮廓及其相对于右下角的偏移坐标
plt.figure()
x_coords = [point[0] for point in transformed_contour]
y_coords = [point[1] for point in transformed_contour]
plt.plot(y_coords,x_coords)
plt.xlabel('y')
plt.ylabel('x')
plt.title('Contours[2]')
plt.show()
![](https://i-blog.csdnimg.cn/blog_migrate/dd75ab6774619ef26db5de048f528ee2.png)
4、根据角点分割出直线
import cv2
import numpy as np
# 读取图像并进行处理
image_path = r"C:\Users\yh\Pictures\1.png"
img = cv2.imread(image_path)
# 图像灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化图像
_, thresholded = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY)
# 轮廓检测
contours, _ = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 选择第三个轮廓进行处理
contour = contours[2]
# 创建空白的二值图像
mask = np.zeros_like(gray)
# 将轮廓绘制在空白图像上
cv2.drawContours(mask, [contour], -1, 255, thickness=cv2.FILLED)
# 将轮廓点转换为Numpy数组
contour_pts = np.squeeze(contour)
# 检测角点
corners = cv2.goodFeaturesToTrack(mask, maxCorners=10, qualityLevel=0.1, minDistance=10)
corners = np.int0(corners)
# 删除冗余的角点
selected_corners = []
for corner in corners:
x, y = corner.ravel()
slope1 = (y - contour_pts[0][1]) / (x - contour_pts[0][0])
slope2 = (contour_pts[-1][1] - y) / (contour_pts[-1][0] - x)
if abs(slope1 - slope2) > 0.1:
selected_corners.append(corner)
selected_corners = np.array(selected_corners)
# 对角点按位置排序
selected_corners = selected_corners[np.argsort(selected_corners[:, 0, 0])]
# 根据角点将轮廓分割
lines = []
start_index = 0
for corner in selected_corners:
x, y = corner.ravel()
# 查找最近的匹配点
distances = np.sqrt(np.sum((contour_pts - [x, y]) ** 2, axis=1))
matched_index = np.argmin(distances)
line = contour_pts[start_index:matched_index + 1]
lines.append(line)
start_index = matched_index + 1
line = contour_pts[start_index:]
lines.append(line)
# 在原图像上绘制分割后的轮廓段和剩余的角点
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] # 不同颜色的直线
line_thickness = 2
for i, line in enumerate(lines):
color = colors[i % len(colors)]
for j in range(len(line) - 1):
cv2.line(img, tuple(line[j]), tuple(line[j + 1]), color, line_thickness)
# 绘制剩余的角点
for corner in selected_corners:
x, y = corner.ravel()
cv2.circle(img, (x, y), 5, (0, 0, 255), -1) # 使用红色圆点标记剩余的角点
# 显示绘制直线和角点后的图像
cv2.imshow('Segmented Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
![](https://i-blog.csdnimg.cn/blog_migrate/253847938b498893bc16aae6e49bf9ab.png)