如何用Python基于二值图像中的车辆白色像素绘制红色停车中线
用Python为二值图像车辆区域绘制红色中线(生成停车线)
使用OpenCV和NumPy即可实现需求,核心思路是先识别二值图中的车辆轮廓,再计算每个轮廓的中线并绘制,具体步骤如下:
1. 导入依赖库
import cv2 import numpy as np
2. 读取并预处理图像
先读取二值图像,转换为彩色图(单通道二值图无法绘制彩色线条);若图像存在噪声,可通过形态学操作清理:
# 读取二值图像(替换为你的图像路径) binary_img = cv2.imread('car_binary.png', cv2.IMREAD_GRAYSCALE) # 转换为彩色图像用于绘制 color_img = cv2.cvtColor(binary_img, cv2.COLOR_GRAY2BGR) # 可选:用开运算去除小噪点 kernel = np.ones((3, 3), np.uint8) binary_img_clean = cv2.morphologyEx(binary_img, cv2.MORPH_OPEN, kernel)
3. 检测车辆轮廓
通过轮廓检测定位二值图中的白色车辆区域:
# 查找白色区域的外部轮廓 contours, _ = cv2.findContours(binary_img_clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
4. 计算并绘制中线
提供两种方案,可根据车辆实际摆放情况选择:
方案1:基于外接矩形的简单中线
适合车辆大致水平/垂直停放的场景,直接取外接矩形的中心竖线(或横线):
# 过滤过小的轮廓(避免误识别噪点,面积阈值根据实际调整) min_contour_area = 500 for cnt in contours: if cv2.contourArea(cnt) < min_contour_area: continue # 获取轮廓的外接矩形 x, y, w, h = cv2.boundingRect(cnt) # 计算中线的x坐标 mid_x = x + w // 2 # 绘制红色中线(BGR格式,红色为(0,0,255),厚度2) cv2.line(color_img, (mid_x, y), (mid_x, y + h), (0, 0, 255), 2)
方案2:基于最小外接矩形的精准中线
如果车辆存在倾斜,用最小外接矩形计算更贴合实际形状的中线:
for cnt in contours: if cv2.contourArea(cnt) < min_contour_area: continue # 计算轮廓的最小外接矩形 rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) width, height = rect[1] if width > height: # 车辆水平摆放,绘制垂直中线 left_mid = ((box[0][0] + box[3][0])//2, (box[0][1] + box[3][1])//2) right_mid = ((box[1][0] + box[2][0])//2, (box[1][1] + box[2][1])//2) mid_x = (left_mid[0] + right_mid[0])//2 top_y = min(box[:, 1]) bottom_y = max(box[:, 1]) cv2.line(color_img, (mid_x, top_y), (mid_x, bottom_y), (0, 0, 255), 2) else: # 车辆垂直摆放,绘制水平中线 top_mid = ((box[0][0] + box[1][0])//2, (box[0][1] + box[1][1])//2) bottom_mid = ((box[2][0] + box[3][0])//2, (box[2][1] + box[3][1])//2) mid_y = (top_mid[1] + bottom_mid[1])//2 left_x = min(box[:, 0]) right_x = max(box[:, 0]) cv2.line(color_img, (left_x, mid_y), (right_x, mid_y), (0, 0, 255), 2)
5. 保存或查看结果
# 显示结果窗口 cv2.imshow('Vehicle Midlines', color_img) cv2.waitKey(0) cv2.destroyAllWindows() # 保存带中线的图像 cv2.imwrite('car_with_parking_lines.png', color_img)
内容的提问来源于stack exchange,提问作者geomaticpoly
相关产品推荐
相关产品推荐

