这个提交包含在:
2025-11-05 23:50:11 +08:00
当前提交 ebb5f13151
共有 3 个文件被更改,包括 506 次插入 和 0 次删除

二进制
demo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 160 KiB

12
requirements.txt 普通文件
查看文件

@ -0,0 +1,12 @@
contourpy==1.3.3
cycler==0.12.1
fonttools==4.60.1
kiwisolver==1.4.9
matplotlib==3.10.7
numpy==2.2.6
opencv-python==4.12.0.88
packaging==25.0
pillow==12.0.0
pyparsing==3.2.5
python-dateutil==2.9.0.post0
six==1.17.0

494
test.py 普通文件
查看文件

@ -0,0 +1,494 @@
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Noto Sans CJK JP', 'Noto Sans CJK SC', 'Noto Sans CJK TC', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
def find_closest_black_lines_advanced(image_path):
# 读取图像
image = cv2.imread(image_path)
if image is None:
print("Error: Could not read image")
return
# 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
height, width = gray.shape
print(f"图像尺寸: {width} x {height}")
# 创建边缘掩码
edge_mask = np.zeros((height, width), dtype=np.uint8)
center_x, center_y = width // 2, height // 2
radius = min(center_x, center_y) * 0.9
cv2.circle(edge_mask, (center_x, center_y), int(radius), 255, -1)
# 显示第一步:原始图像
plt.figure(figsize=(15, 5))
plt.subplot(1, 3, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('1. 原始图像')
plt.axis('off')
plt.subplot(1, 3, 2)
plt.imshow(gray, cmap='gray')
plt.title('2. 灰度图像')
plt.axis('off')
plt.subplot(1, 3, 3)
plt.imshow(edge_mask, cmap='gray')
plt.title('3. 有效区域掩码')
plt.axis('off')
plt.tight_layout()
plt.show()
# 第一步:先识别亮线
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 尝试多种方法识别亮线
# 方法1:高阈值二值化
_, thresh_bright_high = cv2.threshold(blurred, 220, 255, cv2.THRESH_BINARY)
# 方法2:自适应阈值
thresh_bright_adaptive = cv2.adaptiveThreshold(blurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 25, 5)
# 方法3:使用图像顶部亮度参考
top_region = gray[0:50, :] # 取图像顶部区域作为亮度参考
if top_region.size > 0:
bright_reference = np.mean(top_region) + 40
_, thresh_bright_ref = cv2.threshold(blurred, bright_reference, 255, cv2.THRESH_BINARY)
else:
thresh_bright_ref = thresh_bright_high.copy()
# 显示亮线识别尝试
plt.figure(figsize=(15, 10))
plt.subplot(2, 3, 1)
plt.imshow(blurred, cmap='gray')
plt.title('4. 高斯模糊后')
plt.axis('off')
plt.subplot(2, 3, 2)
plt.imshow(thresh_bright_high, cmap='gray')
plt.title('5. 高阈值亮线(220)')
plt.axis('off')
plt.subplot(2, 3, 3)
plt.imshow(thresh_bright_adaptive, cmap='gray')
plt.title('6. 自适应阈值亮线')
plt.axis('off')
plt.subplot(2, 3, 4)
plt.imshow(thresh_bright_ref, cmap='gray')
plt.title(f'7. 参考阈值亮线({int(bright_reference)})')
plt.axis('off')
# 选择最佳的亮线检测结果
# 计算每个结果的亮线面积,选择面积适中的
bright_areas = []
bright_results = [thresh_bright_high, thresh_bright_adaptive, thresh_bright_ref]
result_names = ['高阈值', '自适应', '参考阈值']
for i, result in enumerate(bright_results):
area = np.sum(result == 255)
bright_areas.append(area)
print(f"{result_names[i]}亮线面积: {area}")
# 选择面积适中的结果(避免太大或太小)
median_area = np.median(bright_areas)
best_index = np.argmin(np.abs(bright_areas - median_area))
thresh_bright = bright_results[best_index]
plt.subplot(2, 3, 5)
plt.imshow(thresh_bright, cmap='gray')
plt.title(f'8. 选择的亮线检测\n({result_names[best_index]})')
plt.axis('off')
# 显示亮度直方图
plt.subplot(2, 3, 6)
hist = cv2.calcHist([blurred], [0], None, [256], [0, 256])
plt.plot(hist, color='black')
plt.axvline(x=220, color='red', linestyle='--', label='高阈值(220)')
if top_region.size > 0:
plt.axvline(x=bright_reference, color='blue', linestyle='--', label=f'参考阈值({int(bright_reference)})')
plt.title('9. 图像灰度直方图')
plt.xlabel('灰度值')
plt.ylabel('像素数量')
plt.legend()
plt.tight_layout()
plt.show()
# 对亮线进行形态学处理
horizontal_kernel_bright = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 1))
thresh_bright_clean = cv2.morphologyEx(thresh_bright, cv2.MORPH_CLOSE, horizontal_kernel_bright)
thresh_bright_clean = cv2.bitwise_and(thresh_bright_clean, thresh_bright_clean, mask=edge_mask)
# 提取亮线轮廓
bright_contours, _ = cv2.findContours(thresh_bright_clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(f"找到亮部轮廓数量: {len(bright_contours)}")
if not bright_contours:
print("未找到亮部横线,尝试降低阈值...")
# 尝试使用更低的阈值
_, thresh_bright_low = cv2.threshold(blurred, 180, 255, cv2.THRESH_BINARY)
thresh_bright_low = cv2.morphologyEx(thresh_bright_low, cv2.MORPH_CLOSE, horizontal_kernel_bright)
thresh_bright_low = cv2.bitwise_and(thresh_bright_low, thresh_bright_low, mask=edge_mask)
bright_contours, _ = cv2.findContours(thresh_bright_low, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
thresh_bright_clean = thresh_bright_low
if not bright_contours:
print("仍然未找到亮部横线,请检查图像!")
return
# 筛选亮线
bright_candidates = []
for i, contour in enumerate(bright_contours):
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
aspect_ratio = w / h if h > 0 else 0
if (area > 50 and aspect_ratio > 4 and w > 40):
bright_candidates.append((contour, area, aspect_ratio, (x, y, w, h)))
print(f"亮线候选 {i}: 面积={area:.1f}, 长宽比={aspect_ratio:.1f}, 尺寸={w}x{h}")
if not bright_candidates:
print("筛选后未找到合适的亮部横线")
return
# 选择最可能是目标亮线的(面积最大且位置居中)
def centrality_score(bbox, center_x, center_y):
x, y, w, h = bbox
bbox_center_x = x + w // 2
bbox_center_y = y + h // 2
distance = np.sqrt((bbox_center_x - center_x)**2 + (bbox_center_y - center_y)**2)
return -distance # 距离越小,分数越高
bright_candidates.sort(key=lambda x: (x[1], centrality_score(x[3], center_x, center_y)), reverse=True)
bright_contour = bright_candidates[0][0]
bright_x, bright_y, bright_w, bright_h = bright_candidates[0][3]
bright_center_y = bright_y + bright_h // 2
print(f"选中亮线: 位置({bright_x}, {bright_y}), 尺寸{bright_w}x{bright_h}")
# 创建亮线区域掩码(用于屏蔽亮线区域)
bright_line_mask = np.ones((height, width), dtype=np.uint8) * 255
# 在亮线位置创建一个扩展的屏蔽区域(上下各扩展一些像素)
expand_pixels = max(10, bright_h // 2) # 扩展像素数
y_start = max(0, bright_y - expand_pixels)
y_end = min(height, bright_y + bright_h + expand_pixels)
bright_line_mask[y_start:y_end, :] = 0 # 亮线区域设为0(黑色,即屏蔽)
# 第二步:识别黑线,但屏蔽亮线区域
# 使用更严格的参数识别黑线
thresh_black = cv2.adaptiveThreshold(blurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 25, 8)
# 应用多重掩码:边缘掩码 + 亮线区域掩码
combined_mask = cv2.bitwise_and(edge_mask, bright_line_mask)
thresh_black_masked = cv2.bitwise_and(thresh_black, thresh_black, mask=combined_mask)
# 对黑线进行形态学处理
horizontal_kernel_black = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 3))
# thresh_black_clean = cv2.morphologyEx(thresh_black_masked, cv2.MORPH_OPEN, vertical_kernel)
thresh_black_clean = cv2.morphologyEx(thresh_black_masked, cv2.MORPH_CLOSE, horizontal_kernel_black)
thresh_black_clean = cv2.morphologyEx(thresh_black_clean, cv2.MORPH_CLOSE, horizontal_kernel_black)
# 显示黑线识别过程
plt.figure(figsize=(15, 10))
plt.subplot(2, 3, 1)
plt.imshow(thresh_bright_clean, cmap='gray')
plt.title('10. 最终亮线检测结果')
plt.axis('off')
plt.subplot(2, 3, 2)
plt.imshow(bright_line_mask, cmap='gray')
plt.title('11. 亮线区域屏蔽掩码\n(黑色区域将被屏蔽)')
plt.axis('off')
plt.subplot(2, 3, 3)
plt.imshow(thresh_black, cmap='gray')
plt.title('12. 原始黑线检测')
plt.axis('off')
plt.subplot(2, 3, 4)
plt.imshow(combined_mask, cmap='gray')
plt.title('13. 组合掩码\n(边缘+亮线区域)')
plt.axis('off')
plt.subplot(2, 3, 5)
plt.imshow(thresh_black_masked, cmap='gray')
plt.title('14. 应用掩码后的黑线')
plt.axis('off')
plt.subplot(2, 3, 6)
plt.imshow(thresh_black_clean, cmap='gray')
plt.title('15. 最终黑线检测\n(形态学处理后)')
plt.axis('off')
plt.tight_layout()
plt.show()
# 提取黑色横线轮廓
black_contours, _ = cv2.findContours(thresh_black_clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(f"找到黑色轮廓数量: {len(black_contours)}")
if len(black_contours) < 2:
print("黑色横线数量不足")
return
# 筛选黑色横线
black_line_candidates = []
all_black_lines = [] # 存储所有黑线信息
for i, contour in enumerate(black_contours):
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
aspect_ratio = w / h if h > 0 else 0
# 检查是否在有效区域内
center_x_contour = x + w // 2
center_y_contour = y + h // 2
distance_from_center = np.sqrt((center_x_contour - center_x)**2 + (center_y_contour - center_y)**2)
# 存储所有黑线信息
line_info = {
'contour': contour,
'bbox': (x, y, w, h),
'area': area,
'aspect_ratio': aspect_ratio,
'center': (center_x_contour, center_y_contour),
'distance_from_center': distance_from_center,
'qualified': False,
'distance_to_bright': abs(center_y_contour - bright_center_y)
}
# 严格的筛选条件
if (aspect_ratio > 5 and w > 10 and
distance_from_center < radius * 0.85):
distance_to_bright = abs(center_y_contour - bright_center_y)
black_line_candidates.append((contour, distance_to_bright, area, aspect_ratio,
(x, y, w, h), center_y_contour))
line_info['qualified'] = True
line_info['distance_to_bright'] = distance_to_bright
print(f"黑线候选 {i}: 距离={distance_to_bright:.1f}, 面积={area:.1f}, 长宽比={aspect_ratio:.1f}, 尺寸={w}x{h}")
else:
print(f"黑线 {i}: 不合格 - 面积={area:.1f}, 长宽比={aspect_ratio:.1f}, 尺寸={w}x{h}, 距中心={distance_from_center:.1f}")
all_black_lines.append(line_info)
print(f"筛选后合格的黑色横线数量: {len(black_line_candidates)}")
if len(black_line_candidates) < 2:
print(f"合格的黑色横线数量不足")
# 不直接返回,继续显示所有黑线信息
# 显示最终结果
plt.figure(figsize=(16, 10))
result_image = image.copy()
# 绘制各种区域和线条
cv2.circle(result_image, (center_x, center_y), int(radius), (255, 200, 0), 2)
# 绘制亮线区域屏蔽范围
cv2.rectangle(result_image, (0, y_start), (width, y_end), (255, 100, 0), 1)
# 绘制亮线
cv2.rectangle(result_image, (bright_x, bright_y), (bright_x + bright_w, bright_y + bright_h),
(0, 255, 0), 3)
cv2.putText(result_image, "Target Bright Line", (bright_x, bright_y - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# 绘制所有黑线(合格和不合格的)
for i, line_info in enumerate(all_black_lines):
x, y, w, h = line_info['bbox']
center_x_contour, center_y_contour = line_info['center']
if line_info['qualified']:
# 合格黑线用蓝色标记
color = (255, 0, 0) # 蓝色
text_color = (255, 100, 100)
status = "QUALIFIED"
else:
# 不合格黑线用灰色标记
color = (128, 128, 128) # 灰色
text_color = (200, 200, 200)
status = "DISQUALIFIED"
# 绘制黑线边界框
cv2.rectangle(result_image, (x, y), (x + w, y + h), color, 2)
# 显示黑线信息
info_text = f"Line{i}: {w}x{h} A:{line_info['area']:.1f}"
cv2.putText(result_image, info_text, (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, text_color, 1)
# 显示合格状态
cv2.putText(result_image, status, (x, y - 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, text_color, 1)
# 绘制中心点
cv2.circle(result_image, (center_x_contour, center_y_contour), 3, color, -1)
closest_two_black_lines = []
# 如果存在合格的黑线,绘制最近的两条
if len(black_line_candidates) >= 2:
# 按距离排序,获取最近的两条黑色横线
black_line_candidates.sort(key=lambda x: x[1])
closest_two_black_lines = black_line_candidates[:2]
# 绘制最近的两条黑线(用红色高亮)
for i, (contour, distance, area, aspect_ratio, bbox, center_y) in enumerate(closest_two_black_lines):
x, y, w, h = bbox
cv2.rectangle(result_image, (x, y), (x + w, y + h), (0, 0, 255), 4)
cv2.putText(result_image, f"Closest Black {i+1}", (x, y - 45),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# 绘制距离线
cv2.line(result_image, (bright_x + bright_w // 2, bright_center_y),
(x + w // 2, center_y), (0, 255, 255), 2)
cv2.putText(result_image, f"{distance:.1f}px",
((bright_x + bright_w // 2 + x + w // 2) // 2,
(bright_center_y + center_y) // 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
plt.subplot(2, 2, 1)
plt.imshow(cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB))
plt.title('16. 最终检测结果\n(绿:目标亮线, 红:最近黑线, 蓝:合格黑线, 灰:不合格黑线)')
plt.axis('off')
# 在控制台输出所有黑线的详细信息
print("\n=== 所有黑线详细信息 ===")
for i, line_info in enumerate(all_black_lines):
x, y, w, h = line_info['bbox']
status = "合格" if line_info['qualified'] else "不合格"
print(f"黑线 {i}: 位置({x},{y}) 尺寸({w}x{h}) 面积{line_info['area']:.1f} "
f"长宽比{line_info['aspect_ratio']:.1f} 状态:{status}")
# 显示检测统计
plt.subplot(2, 2, 2)
stats_data = [len(bright_contours), len(black_contours), len(black_line_candidates)]
stats_labels = ['原始亮线', '原始黑线', '合格黑线']
colors = ['lightgreen', 'lightcoral', 'lightblue']
bars = plt.bar(stats_labels, stats_data, color=colors)
plt.title('17. 检测统计')
plt.ylabel('数量')
for bar, value in zip(bars, stats_data):
plt.text(bar.get_x() + bar.get_width()/2, value + 0.1, str(value),
ha='center', va='bottom', fontweight='bold')
# 显示距离信息
plt.subplot(2, 2, 3)
distances = [line[1] for line in closest_two_black_lines]
plt.bar(['最近黑线1', '最近黑线2'], distances, color=['red', 'darkred'], alpha=0.7)
plt.title('18. 距离亮线的像素距离')
plt.ylabel('距离 (像素)')
for i, dist in enumerate(distances):
plt.text(i, dist + 0.5, f'{dist:.1f}px', ha='center', va='bottom', fontweight='bold')
# 显示详细信息
plt.subplot(2, 2, 4)
info_text = f"""目标亮线:
位置: ({bright_x}, {bright_y})
尺寸: {bright_w} x {bright_h}
中心Y: {bright_center_y}
屏蔽区域:
上下扩展: {expand_pixels}像素
屏蔽范围: Y={y_start}-{y_end}
检测到的最近黑线:
1号: {distances[0]:.1f}像素
2号: {distances[1]:.1f}像素
"""
plt.text(0.05, 0.95, info_text, fontsize=9, verticalalignment='top',
bbox=dict(boxstyle="round,pad=0.5", facecolor="lightyellow"))
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.title('19. 详细信息')
plt.axis('off')
plt.tight_layout()
plt.show()
bright_center_y = bright_center_y # 亮线中心Y坐标(从您的代码中已有)
# 从最近的两个黑线中提取中心Y坐标
closest_black_centers = []
for contour, distance, area, aspect_ratio, bbox, center_y in closest_two_black_lines:
closest_black_centers.append(center_y)
# 按Y坐标排序(从上到下)
closest_black_centers.sort()
# 计算比值
if len(closest_black_centers) == 2:
# 亮线到下方最近黑线的距离
distance_bright_to_lower = abs(bright_center_y - closest_black_centers[1])
# 两个黑线中点之间的距离
distance_between_black_lines = abs(closest_black_centers[1] - closest_black_centers[0])
# 计算比值
if distance_between_black_lines > 0:
ratio = distance_bright_to_lower / distance_between_black_lines
print(f"\n=== 距离比值计算 ===")
print(f"亮线中心Y: {bright_center_y:.1f}")
print(f"上方黑线中心Y: {closest_black_centers[0]:.1f}")
print(f"下方黑线中心Y: {closest_black_centers[1]:.1f}")
print(f"亮线-下方黑线距离: {distance_bright_to_lower:.1f} 像素")
print(f"两黑线间距离: {distance_between_black_lines:.1f} 像素")
print(f"距离比值: {ratio:.3f}")
# 在图表中显示这个比值
plt.subplot(2, 2, 4) # 使用您现有的详细信息子图
info_text = f"""目标亮线:
位置: ({bright_x}, {bright_y})
尺寸: {bright_w} x {bright_h}
中心Y: {bright_center_y:.1f}
屏蔽区域:
上下扩展: {expand_pixels}像素
屏蔽范围: Y={y_start}-{y_end}
检测到的最近黑线:
1号: {distances[0]:.1f}像素
2号: {distances[1]:.1f}像素
距离比值: {ratio:.5f}
"""
plt.text(0.05, 0.95, info_text, fontsize=9, verticalalignment='top',
bbox=dict(boxstyle="round,pad=0.5", facecolor="lightyellow"))
plt.show()
return closest_two_black_lines, ratio
else:
print("警告:两个黑线中心距离为0,无法计算比值")
return closest_two_black_lines, None
else:
print("警告:未找到两个最近的黑线")
return closest_two_black_lines, None
# 使用示例
if __name__ == "__main__":
image_path = "demo.png" # 替换为你的图像路径
closest_lines = find_closest_black_lines_advanced(image_path)
if closest_lines:
print("\n✅ 检测成功!")
else:
print("\n❌ 检测失败,请检查图像路径或调整参数")