file:/D:/python文件/pythonProject2/yolov5/python_cc.py
这个提交包含在:
二进制
06_thresh_bright_adaptive.jpg
普通文件
二进制
06_thresh_bright_adaptive.jpg
普通文件
二进制文件未显示。
|
之后 宽度: | 高度: | 大小: 563 KiB |
340
findit.py
普通文件
340
findit.py
普通文件
@ -0,0 +1,340 @@
|
|||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
import pytesseract
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
from sklearn.cluster import KMeans
|
||||||
|
|
||||||
|
|
||||||
|
tesseract_path = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
|
||||||
|
if os.path.exists(tesseract_path):
|
||||||
|
pytesseract.pytesseract.tesseract_cmd = tesseract_path
|
||||||
|
else:
|
||||||
|
print(f"警告:Tesseract 路径不存在 -> {tesseract_path}")
|
||||||
|
print("请修改代码中的 tesseract_path 变量")
|
||||||
|
|
||||||
|
def read_caliper(image_path, debug=False):
|
||||||
|
# 1. 读取图像
|
||||||
|
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
|
||||||
|
if img is None:
|
||||||
|
raise ValueError("无法读取图像,请检查路径")
|
||||||
|
h_img, w_img = img.shape
|
||||||
|
|
||||||
|
# 确保图像是二值图(0和255)
|
||||||
|
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
|
||||||
|
|
||||||
|
# 2. 检测垂直线段(刻度线)
|
||||||
|
lines = detect_lines_via_morphology(binary, h_img, w_img, debug)
|
||||||
|
if len(lines) < 10:
|
||||||
|
print("形态学检测刻度线数量不足,尝试霍夫线变换...")
|
||||||
|
lines = detect_lines_via_hough(binary, h_img, w_img, debug)
|
||||||
|
|
||||||
|
if len(lines) < 10:
|
||||||
|
raise RuntimeError(f"检测到刻度线数量不足({len(lines)}),请检查图像或调整参数")
|
||||||
|
|
||||||
|
# 3. 根据高度区分主尺线和游标线
|
||||||
|
main_lines, cursor_lines = classify_lines_by_height(lines, h_img)
|
||||||
|
|
||||||
|
if len(main_lines) < 5 or len(cursor_lines) < 5:
|
||||||
|
raise RuntimeError("主尺线或游标线数量不足")
|
||||||
|
|
||||||
|
main_lines = sorted(main_lines)
|
||||||
|
cursor_lines = sorted(cursor_lines)
|
||||||
|
print(f"主尺线数量: {len(main_lines)}, 游标线数量: {len(cursor_lines)}")
|
||||||
|
|
||||||
|
# 4. 计算主尺刻度间距
|
||||||
|
pixel_per_mm = compute_scale_spacing(main_lines)
|
||||||
|
print(f"主尺刻度间距: {pixel_per_mm:.2f} 像素/mm")
|
||||||
|
|
||||||
|
# 5. OCR识别主尺数字
|
||||||
|
digits = recognize_digits(binary, debug)
|
||||||
|
if len(digits) < 2:
|
||||||
|
raise RuntimeError(f"未能识别出足够的数字(仅{len(digits)}个),请检查图像或Tesseract安装")
|
||||||
|
digits.sort(key=lambda d: d[0])
|
||||||
|
print(f"识别到的数字: {digits}")
|
||||||
|
|
||||||
|
# 6. 定位游标零刻度线(默认最左边游标线)
|
||||||
|
zero_line_x = cursor_lines[0]
|
||||||
|
|
||||||
|
# 7. 计算整数部分
|
||||||
|
integer_part = compute_integer_part(digits, main_lines, zero_line_x, pixel_per_mm)
|
||||||
|
print(f"整数部分: {integer_part} mm")
|
||||||
|
|
||||||
|
# 【新增】计算零线位于第几个格子(即整数部分的值,表示从0毫米开始的毫米数)
|
||||||
|
grid_number = integer_part
|
||||||
|
print(f"游标0刻度线位于第 {grid_number} 个格子(毫米位置)")
|
||||||
|
|
||||||
|
# 8. 计算小数部分
|
||||||
|
fractional = compute_fractional_part(cursor_lines, main_lines, pixel_per_mm, debug)
|
||||||
|
print(f"小数部分: {fractional:.2f} mm")
|
||||||
|
|
||||||
|
# 【新增】根据用户要求:若游标读数为0,则额外加1mm
|
||||||
|
if abs(fractional) < 1e-6: # 浮点数判0
|
||||||
|
result = integer_part + 1.0
|
||||||
|
print(f"游标读数为0,额外加1mm,最终读数 = {result:.2f} mm")
|
||||||
|
else:
|
||||||
|
result = integer_part + fractional
|
||||||
|
print(f"最终读数 = {result:.2f} mm")
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
# 以下函数均未改动(与原代码相同)
|
||||||
|
def detect_lines_via_morphology(binary, h_img, w_img, debug):
|
||||||
|
min_h = h_img // 50
|
||||||
|
max_w = w_img // 80
|
||||||
|
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 3))
|
||||||
|
morphed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations=1)
|
||||||
|
|
||||||
|
contours, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||||
|
|
||||||
|
lines = []
|
||||||
|
for cnt in contours:
|
||||||
|
x, y, w, h = cv2.boundingRect(cnt)
|
||||||
|
if h >= min_h and w <= max_w and w * h > 50:
|
||||||
|
center_x = x + w // 2
|
||||||
|
center_y = y + h // 2
|
||||||
|
lines.append((center_x, center_y, h))
|
||||||
|
|
||||||
|
if debug:
|
||||||
|
vis = cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)
|
||||||
|
for (cx, cy, h) in lines:
|
||||||
|
cv2.line(vis, (cx, cy - h // 2), (cx, cy + h // 2), (0, 255, 0), 1)
|
||||||
|
cv2.imshow("Detected Lines (Morphology)", vis)
|
||||||
|
cv2.waitKey(0)
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
return lines
|
||||||
|
|
||||||
|
def detect_lines_via_hough(binary, h_img, w_img, debug):
|
||||||
|
edges = cv2.Canny(binary, 50, 150)
|
||||||
|
lines_p = cv2.HoughLinesP(edges, rho=1, theta=np.pi / 180, threshold=20,
|
||||||
|
minLineLength=h_img // 50, maxLineGap=5)
|
||||||
|
|
||||||
|
lines = []
|
||||||
|
if lines_p is not None:
|
||||||
|
for line in lines_p:
|
||||||
|
x1, y1, x2, y2 = line[0]
|
||||||
|
angle = abs(math.degrees(math.atan2(y2 - y1, x2 - x1)))
|
||||||
|
if 80 <= angle <= 100:
|
||||||
|
length = abs(y2 - y1)
|
||||||
|
if length > h_img // 30:
|
||||||
|
cx = (x1 + x2) // 2
|
||||||
|
cy = (y1 + y2) // 2
|
||||||
|
lines.append((cx, cy, length))
|
||||||
|
|
||||||
|
if debug:
|
||||||
|
vis = cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)
|
||||||
|
for (cx, cy, h) in lines:
|
||||||
|
cv2.line(vis, (cx, cy - h // 2), (cx, cy + h // 2), (0, 255, 0), 1)
|
||||||
|
cv2.imshow("Detected Lines (Hough)", vis)
|
||||||
|
cv2.waitKey(0)
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
return lines
|
||||||
|
|
||||||
|
def classify_lines_by_height(lines, img_h):
|
||||||
|
heights = np.array([h for (_, _, h) in lines]).reshape(-1, 1)
|
||||||
|
kmeans = KMeans(n_clusters=2, random_state=0, n_init=10).fit(heights)
|
||||||
|
labels = kmeans.labels_
|
||||||
|
cluster_means = [np.mean(heights[labels == i]) for i in range(2)]
|
||||||
|
main_cluster = np.argmax(cluster_means)
|
||||||
|
|
||||||
|
main_lines = []
|
||||||
|
cursor_lines = []
|
||||||
|
for (cx, cy, h), label in zip(lines, labels):
|
||||||
|
if label == main_cluster:
|
||||||
|
main_lines.append(cx)
|
||||||
|
else:
|
||||||
|
cursor_lines.append(cx)
|
||||||
|
return main_lines, cursor_lines
|
||||||
|
|
||||||
|
def compute_scale_spacing(main_lines):
|
||||||
|
diffs = np.diff(main_lines)
|
||||||
|
if len(diffs) < 3:
|
||||||
|
return np.mean(diffs)
|
||||||
|
q_low = np.percentile(diffs, 10)
|
||||||
|
q_high = np.percentile(diffs, 90)
|
||||||
|
valid_diffs = diffs[(diffs >= q_low) & (diffs <= q_high)]
|
||||||
|
return np.mean(valid_diffs)
|
||||||
|
|
||||||
|
def recognize_digits(binary, debug=False):
|
||||||
|
if np.mean(binary) > 127:
|
||||||
|
ocr_img = cv2.bitwise_not(binary)
|
||||||
|
else:
|
||||||
|
ocr_img = binary
|
||||||
|
|
||||||
|
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
|
||||||
|
ocr_img = cv2.morphologyEx(ocr_img, cv2.MORPH_CLOSE, kernel, iterations=1)
|
||||||
|
|
||||||
|
contours, _ = cv2.findContours(ocr_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||||
|
candidate_rects = []
|
||||||
|
h_img = ocr_img.shape[0]
|
||||||
|
|
||||||
|
min_h = h_img // 40
|
||||||
|
for cnt in contours:
|
||||||
|
x, y, w, h = cv2.boundingRect(cnt)
|
||||||
|
aspect = w / h if h > 0 else 0
|
||||||
|
if h > min_h and 0.2 < aspect < 2.0 and w * h > 100:
|
||||||
|
candidate_rects.append((x, y, w, h))
|
||||||
|
|
||||||
|
if debug:
|
||||||
|
print(f"检测到 {len(candidate_rects)} 个候选数字区域")
|
||||||
|
|
||||||
|
digits = []
|
||||||
|
for (x, y, w, h) in candidate_rects:
|
||||||
|
roi = ocr_img[y:y + h, x:x + w]
|
||||||
|
roi = cv2.copyMakeBorder(roi, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=255)
|
||||||
|
target_h = 64
|
||||||
|
scale = target_h / roi.shape[0]
|
||||||
|
roi = cv2.resize(roi, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
|
||||||
|
_, roi = cv2.threshold(roi, 127, 255, cv2.THRESH_BINARY)
|
||||||
|
|
||||||
|
if debug:
|
||||||
|
cv2.imshow(f"ROI at x={x}", roi)
|
||||||
|
cv2.waitKey(1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
text = pytesseract.image_to_string(
|
||||||
|
roi,
|
||||||
|
config='--psm 8 -c tessedit_char_whitelist=0123456789'
|
||||||
|
).strip()
|
||||||
|
if debug:
|
||||||
|
print(f"ROI (x={x}) OCR 结果: '{text}'")
|
||||||
|
if text.isdigit() and len(text) <= 2:
|
||||||
|
digit_val = int(text[0])
|
||||||
|
digits.append((x + w // 2, digit_val))
|
||||||
|
else:
|
||||||
|
matched_val = match_digit_template(roi)
|
||||||
|
if matched_val is not None:
|
||||||
|
digits.append((x + w // 2, matched_val))
|
||||||
|
if debug:
|
||||||
|
print(f"模板匹配成功: {matched_val}")
|
||||||
|
except Exception as e:
|
||||||
|
if debug:
|
||||||
|
print(f"OCR 异常: {e}")
|
||||||
|
|
||||||
|
digits = deduplicate_digits(digits, threshold=20)
|
||||||
|
digits.sort(key=lambda d: d[0])
|
||||||
|
|
||||||
|
if len(digits) < 2:
|
||||||
|
if debug:
|
||||||
|
print("候选区识别不足,尝试整图 OCR...")
|
||||||
|
digits = whole_image_ocr(ocr_img, debug)
|
||||||
|
|
||||||
|
if len(digits) < 2:
|
||||||
|
raise RuntimeError(f"未能识别出足够的数字(仅 {len(digits)} 个),请检查图像或预处理")
|
||||||
|
|
||||||
|
return digits
|
||||||
|
|
||||||
|
def match_digit_template(roi):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def deduplicate_digits(digits, threshold):
|
||||||
|
if not digits:
|
||||||
|
return []
|
||||||
|
digits.sort(key=lambda d: d[0])
|
||||||
|
unique = [digits[0]]
|
||||||
|
for d in digits[1:]:
|
||||||
|
if abs(d[0] - unique[-1][0]) > threshold:
|
||||||
|
unique.append(d)
|
||||||
|
return unique
|
||||||
|
|
||||||
|
def whole_image_ocr(ocr_img, debug=False):
|
||||||
|
try:
|
||||||
|
data = pytesseract.image_to_data(
|
||||||
|
ocr_img,
|
||||||
|
config='--psm 6 -c tessedit_char_whitelist=0123456789',
|
||||||
|
output_type=pytesseract.Output.DICT
|
||||||
|
)
|
||||||
|
digits = []
|
||||||
|
for i in range(len(data['text'])):
|
||||||
|
text = data['text'][i].strip()
|
||||||
|
if text.isdigit():
|
||||||
|
x = data['left'][i] + data['width'][i] // 2
|
||||||
|
digits.append((x, int(text[0])))
|
||||||
|
if debug:
|
||||||
|
print(f"整图 OCR: 数字 {text[0]} 位于 x={x}")
|
||||||
|
return digits
|
||||||
|
except Exception as e:
|
||||||
|
if debug:
|
||||||
|
print(f"整图 OCR 失败: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def compute_integer_part(digits, main_lines, zero_line_x, pixel_per_mm):
|
||||||
|
"""
|
||||||
|
计算整数部分(毫米)
|
||||||
|
假设 digits 中的数字代表厘米(如 2 代表 20mm),相邻数字间距为 10mm。
|
||||||
|
"""
|
||||||
|
# 找到零线左侧最近和右侧最近的数字
|
||||||
|
left_digit = None
|
||||||
|
right_digit = None
|
||||||
|
for (dx, val) in digits:
|
||||||
|
if dx < zero_line_x:
|
||||||
|
left_digit = (dx, val)
|
||||||
|
else:
|
||||||
|
right_digit = (dx, val)
|
||||||
|
break
|
||||||
|
|
||||||
|
# 如果零线在所有数字左侧,取最左边数字为参考,右侧用下一个数字(如果有)
|
||||||
|
if left_digit is None:
|
||||||
|
left_digit = digits[0]
|
||||||
|
right_digit = digits[1] if len(digits) > 1 else None
|
||||||
|
# 如果零线在所有数字右侧,取最右边数字为参考
|
||||||
|
elif right_digit is None:
|
||||||
|
right_digit = digits[-1]
|
||||||
|
left_digit = digits[-2] if len(digits) > 1 else None
|
||||||
|
|
||||||
|
if left_digit is None or right_digit is None:
|
||||||
|
raise RuntimeError("无法定位零线两侧的数字")
|
||||||
|
|
||||||
|
# 找到左边数字对应的主尺线(取最近的主尺线)
|
||||||
|
left_line_x = min(main_lines, key=lambda mx: abs(mx - left_digit[0]))
|
||||||
|
|
||||||
|
# 统计从左边数字刻度线到零线之间的主尺线数量(不包括左边线本身)
|
||||||
|
count = sum(1 for mx in main_lines if left_line_x < mx < zero_line_x)
|
||||||
|
|
||||||
|
# 整数部分 = 左边数字值 * 10 + 中间刻度数
|
||||||
|
integer_part = left_digit[1] * 10 + count
|
||||||
|
return integer_part
|
||||||
|
|
||||||
|
def compute_fractional_part(cursor_lines, main_lines, pixel_per_mm, debug=False):
|
||||||
|
"""改进版:通过偏移最小化确定对齐游标线"""
|
||||||
|
if len(cursor_lines) < 2:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
zero_x = cursor_lines[0]
|
||||||
|
main_spacing_px = pixel_per_mm
|
||||||
|
main_array = np.array(main_lines)
|
||||||
|
|
||||||
|
offsets = [] # 存储 (索引, 偏移)
|
||||||
|
for idx, cx in enumerate(cursor_lines[1:], start=1):
|
||||||
|
nearest_main = main_array[np.argmin(np.abs(main_array - cx))]
|
||||||
|
offset = abs(cx - nearest_main)
|
||||||
|
offsets.append((idx, offset))
|
||||||
|
if debug:
|
||||||
|
print(f"游标线 {idx}: x={cx:.2f}, 最近主尺线={nearest_main:.2f}, 偏移={offset:.2f} px")
|
||||||
|
|
||||||
|
# 按偏移排序
|
||||||
|
offsets.sort(key=lambda x: x[1])
|
||||||
|
best_idx, best_offset = offsets[0]
|
||||||
|
|
||||||
|
# 置信度判断
|
||||||
|
if len(offsets) > 1 and best_offset > 0.6 * offsets[1][1]:
|
||||||
|
print(f"警告:最小偏移 {best_offset:.2f} px 与次小偏移 {offsets[1][1]:.2f} px 差距不足,可能误判,小数部分设为0")
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
if best_offset > main_spacing_px * 0.25:
|
||||||
|
print(f"警告:最小偏移 {best_offset:.2f} px 过大(> 主尺间距的1/4),小数部分设为0")
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
fractional = best_idx * 0.02
|
||||||
|
print(f"最佳对齐游标线索引: {best_idx}, 偏移={best_offset:.2f} px, 小数部分: {fractional:.2f} mm")
|
||||||
|
return fractional
|
||||||
|
|
||||||
|
def compute_fractional_part_advanced(cursor_lines, main_lines, pixel_per_mm, debug=False):
|
||||||
|
return compute_fractional_part(cursor_lines, main_lines, pixel_per_mm, debug)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
reading = read_caliper("06_thresh_bright_adaptive.jpg", debug=True)
|
||||||
|
print(f"最终读数(含修正): {reading:.2f} mm")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"读数失败: {e}")
|
||||||
350
python_cc.py
普通文件
350
python_cc.py
普通文件
@ -0,0 +1,350 @@
|
|||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import os # 新增导入
|
||||||
|
|
||||||
|
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_picture_line_advance(image_path, output_dir=None):
|
||||||
|
"""
|
||||||
|
识别图像中的亮线和附近的两条黑线,并计算距离比值。
|
||||||
|
如果指定 output_dir,则将中间结果和最终结果保存为图片文件。
|
||||||
|
"""
|
||||||
|
if output_dir:
|
||||||
|
os.makedirs(output_dir, exist_ok=True)
|
||||||
|
print(f"结果将保存到目录: {output_dir}")
|
||||||
|
|
||||||
|
def save_image(img, filename):
|
||||||
|
if output_dir and img is not None:
|
||||||
|
path = os.path.join(output_dir, filename)
|
||||||
|
cv2.imwrite(path, img)
|
||||||
|
print(f"已保存: {path}")
|
||||||
|
|
||||||
|
image = cv2.imread(image_path)
|
||||||
|
if image is None:
|
||||||
|
print('无法读取图像')
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 保存原始图像
|
||||||
|
save_image(image, "01_original.jpg")
|
||||||
|
|
||||||
|
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
||||||
|
save_image(gray, "02_gray.jpg")
|
||||||
|
|
||||||
|
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)
|
||||||
|
save_image(edge_mask, "03_edge_mask.jpg")
|
||||||
|
|
||||||
|
# 显示第一步
|
||||||
|
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)
|
||||||
|
save_image(blurred, "04_blurred.jpg")
|
||||||
|
|
||||||
|
# 多种亮线识别方法
|
||||||
|
_, thresh_bright_high = cv2.threshold(blurred, 220, 255, cv2.THRESH_BINARY)
|
||||||
|
save_image(thresh_bright_high, "05_thresh_bright_high.jpg")
|
||||||
|
|
||||||
|
thresh_bright_adaptive = cv2.adaptiveThreshold(blurred, 255,
|
||||||
|
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||||
|
cv2.THRESH_BINARY, 25, 5)
|
||||||
|
save_image(thresh_bright_adaptive, "06_thresh_bright_adaptive.jpg")
|
||||||
|
|
||||||
|
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()
|
||||||
|
save_image(thresh_bright_ref, "07_thresh_bright_ref.jpg")
|
||||||
|
|
||||||
|
# 显示亮线识别尝试
|
||||||
|
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_results = [thresh_bright_high, thresh_bright_adaptive, thresh_bright_ref]
|
||||||
|
result_names = ['高阈值', '自适应', '参考阈值']
|
||||||
|
bright_areas = [np.sum(r==255) for r in bright_results]
|
||||||
|
for n, a in zip(result_names, bright_areas):
|
||||||
|
print(f"{n}亮线面积: {a}")
|
||||||
|
median_area = np.median(bright_areas)
|
||||||
|
best_index = np.argmin(np.abs(bright_areas - median_area))
|
||||||
|
thresh_bright = bright_results[best_index]
|
||||||
|
save_image(thresh_bright, "08_thresh_bright_selected.jpg")
|
||||||
|
|
||||||
|
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)
|
||||||
|
save_image(thresh_bright_clean, "09_thresh_bright_clean.jpg")
|
||||||
|
|
||||||
|
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
|
||||||
|
save_image(thresh_bright_clean, "09_thresh_bright_clean_low.jpg")
|
||||||
|
|
||||||
|
if not bright_contours:
|
||||||
|
print("仍然未找到亮部横线,请检查图像!")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 筛选亮线
|
||||||
|
bright_candidates = []
|
||||||
|
for i, cnt in enumerate(bright_contours):
|
||||||
|
x, y, w, h = cv2.boundingRect(cnt)
|
||||||
|
area = cv2.contourArea(cnt)
|
||||||
|
aspect_ratio = w/h if h>0 else 0
|
||||||
|
if area > 50 and aspect_ratio > 4 and w > 40:
|
||||||
|
bright_candidates.append((cnt, area, aspect_ratio, (x,y,w,h)))
|
||||||
|
print(f"亮线候选 {i}: 面积={area:.1f}, 长宽比={aspect_ratio:.1f}, 尺寸={w}x{h}")
|
||||||
|
|
||||||
|
if not bright_candidates:
|
||||||
|
print("筛选后未找到合适的亮部横线")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def centrality_score(bbox, cx, cy):
|
||||||
|
x,y,w,h = bbox
|
||||||
|
bcx = x + w//2
|
||||||
|
bcy = y + h//2
|
||||||
|
return -np.sqrt((bcx-cx)**2 + (bcy-cy)**2)
|
||||||
|
|
||||||
|
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
|
||||||
|
save_image(bright_line_mask, "10_bright_line_mask.jpg")
|
||||||
|
|
||||||
|
# 黑线检测
|
||||||
|
thresh_black = cv2.adaptiveThreshold(blurred, 255,
|
||||||
|
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||||
|
cv2.THRESH_BINARY_INV, 25, 8)
|
||||||
|
save_image(thresh_black, "11_thresh_black.jpg")
|
||||||
|
|
||||||
|
combined_mask = cv2.bitwise_and(edge_mask, bright_line_mask)
|
||||||
|
save_image(combined_mask, "12_combined_mask.jpg")
|
||||||
|
|
||||||
|
thresh_black_masked = cv2.bitwise_and(thresh_black, thresh_black, mask=combined_mask)
|
||||||
|
save_image(thresh_black_masked, "13_thresh_black_masked.jpg")
|
||||||
|
|
||||||
|
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_CLOSE, horizontal_kernel_black)
|
||||||
|
thresh_black_clean = cv2.morphologyEx(thresh_black_clean, cv2.MORPH_CLOSE, horizontal_kernel_black)
|
||||||
|
save_image(thresh_black_clean, "14_thresh_black_clean.jpg")
|
||||||
|
|
||||||
|
# 显示黑线识别过程
|
||||||
|
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. 亮线区域屏蔽掩码'); 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. 组合掩码'); 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. 最终黑线检测'); 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("黑色横线数量不足")
|
||||||
|
# 仍继续绘制,显示所有黑线
|
||||||
|
|
||||||
|
# 筛选黑色横线
|
||||||
|
black_line_candidates = []
|
||||||
|
all_black_lines = []
|
||||||
|
for i, cnt in enumerate(black_contours):
|
||||||
|
x, y, w, h = cv2.boundingRect(cnt)
|
||||||
|
area = cv2.contourArea(cnt)
|
||||||
|
aspect_ratio = w/h if h>0 else 0
|
||||||
|
cx_cnt, cy_cnt = x + w//2, y + h//2
|
||||||
|
dist_from_center = np.sqrt((cx_cnt - center_x)**2 + (cy_cnt - center_y)**2)
|
||||||
|
line_info = {
|
||||||
|
'contour': cnt,
|
||||||
|
'bbox': (x,y,w,h),
|
||||||
|
'area': area,
|
||||||
|
'aspect_ratio': aspect_ratio,
|
||||||
|
'center': (cx_cnt, cy_cnt),
|
||||||
|
'distance_from_center': dist_from_center,
|
||||||
|
'qualified': False,
|
||||||
|
'distance_to_bright': abs(cy_cnt - bright_center_y)
|
||||||
|
}
|
||||||
|
if aspect_ratio > 5 and w > 10 and dist_from_center < radius * 0.85:
|
||||||
|
d2bright = abs(cy_cnt - bright_center_y)
|
||||||
|
black_line_candidates.append((cnt, d2bright, area, aspect_ratio, (x,y,w,h), cy_cnt))
|
||||||
|
line_info['qualified'] = True
|
||||||
|
line_info['distance_to_bright'] = d2bright
|
||||||
|
print(f"黑线候选 {i}: 距离={d2bright:.1f}, 面积={area:.1f}, 长宽比={aspect_ratio:.1f}, 尺寸={w}x{h}")
|
||||||
|
else:
|
||||||
|
print(f"黑线 {i}: 不合格 - 面积={area:.1f}, 长宽比={aspect_ratio:.1f}, 尺寸={w}x{h}, 距中心={dist_from_center:.1f}")
|
||||||
|
all_black_lines.append(line_info)
|
||||||
|
|
||||||
|
print(f"筛选后合格的黑色横线数量: {len(black_line_candidates)}")
|
||||||
|
|
||||||
|
# 绘制最终结果
|
||||||
|
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, info in enumerate(all_black_lines):
|
||||||
|
x,y,w,h = info['bbox']
|
||||||
|
cx, cy = info['center']
|
||||||
|
if 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)
|
||||||
|
cv2.putText(result_image, f"Line{i}: {w}x{h} A:{info['area']:.1f}", (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, (cx,cy), 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, (cnt, dist, area, ar, bbox, cy) 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, cy), (0,255,255), 2)
|
||||||
|
cv2.putText(result_image, f"{dist:.1f}px", ((bright_x+bright_w//2 + x+w//2)//2, (bright_center_y+cy)//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')
|
||||||
|
|
||||||
|
# 保存最终结果
|
||||||
|
save_image(result_image, "15_result_image.jpg")
|
||||||
|
|
||||||
|
# 统计图
|
||||||
|
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, v in zip(bars, stats_data):
|
||||||
|
plt.text(bar.get_x()+bar.get_width()/2, v+0.1, str(v), ha='center', va='bottom', fontweight='bold')
|
||||||
|
|
||||||
|
# 距离图
|
||||||
|
plt.subplot(2,2,3)
|
||||||
|
if len(closest_two_black_lines) >= 2:
|
||||||
|
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, d in enumerate(distances):
|
||||||
|
plt.text(i, d+0.5, f'{d:.1f}px', ha='center', va='bottom', fontweight='bold')
|
||||||
|
else:
|
||||||
|
plt.text(0.5, 0.5, '不足两条合格黑线', ha='center', va='center', fontsize=12)
|
||||||
|
|
||||||
|
# 详细信息
|
||||||
|
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}
|
||||||
|
|
||||||
|
检测到的最近黑线:"""
|
||||||
|
if len(closest_two_black_lines) >= 2:
|
||||||
|
d1, d2 = distances[0], distances[1]
|
||||||
|
info_text += f"""
|
||||||
|
1号: {d1:.1f}像素
|
||||||
|
2号: {d2:.1f}像素"""
|
||||||
|
# 计算比值
|
||||||
|
bright_cy = bright_center_y
|
||||||
|
black_centers = [line[5] for line in closest_two_black_lines] # 中心Y
|
||||||
|
black_centers.sort()
|
||||||
|
dist_bright_to_lower = abs(bright_cy - black_centers[1])
|
||||||
|
dist_black_between = abs(black_centers[1] - black_centers[0])
|
||||||
|
if dist_black_between > 0:
|
||||||
|
ratio = dist_bright_to_lower / dist_black_between
|
||||||
|
info_text += f"""
|
||||||
|
亮线-下方黑线: {dist_bright_to_lower:.1f}px
|
||||||
|
两黑线间距离: {dist_black_between:.1f}px
|
||||||
|
距离比值: {ratio:.5f}"""
|
||||||
|
else:
|
||||||
|
info_text += "\n 不足两条合格黑线"
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
if len(closest_two_black_lines) >= 2:
|
||||||
|
return closest_two_black_lines, ratio
|
||||||
|
else:
|
||||||
|
return closest_two_black_lines, None
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
image_path = "6c31943709ee841daa8979a2c6de280e.jpg"
|
||||||
|
# 指定输出目录,所有中间结果将保存在 ./output 文件夹中
|
||||||
|
closest_lines, ratio = find_picture_line_advance(image_path, output_dir="output")
|
||||||
|
if closest_lines:
|
||||||
|
print(f"\n✅ 检测成功!距离比值: {ratio:.5f}")
|
||||||
|
else:
|
||||||
|
print("\n❌ 检测失败,请检查图像路径或调整参数")
|
||||||
在新工单中引用
屏蔽一个用户