1.将mask面生成inline.txt文件,共两步
1)将面转线
import os
import cv2
import numpy as np
def reduce_clusters(arr):
result = []
last_value = None
for value in arr:
if value == 255:
if last_value != 255:
result.append(value)
last_value = value
else:
result.append(value)
last_value = value
return result
def find_continuous_groups_indices(lst, target_value):
group_indices = []
current_group = []
for i, value in enumerate(lst):
if value == target_value:
current_group.append(i)
else:
if current_group:
# 计算当前组的中值索引
mid_index = current_group[len(current_group) // 2]
group_indices.append(mid_index)
current_group = [] # 重置当前组
# 处理列表末尾可能存在的最后一组
if current_group:
mid_index = current_group[len(current_group) // 2]
group_indices.append(mid_index)
return group_indices
def extract_row_pixels(image_path,save_Path):
# 读取图像
files = os.listdir(image_path)
for file in files:
imgpath = os.path.join(image_path,file)
savePath = os.path.join(save_Path,file)
image = cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)
if image is None:
print(f"Failed to load image from {imgpath}")
return None
# 确保图像是二值图像(只包含0和255)
# _, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
imgshape = (1300, 3400)
zero_img = np.zeros(imgshape)
# 遍历每一行,保留每一行像素值
for row in range(image.shape[0]):
# 取出当前行的像素值
row_pixels = image[row, :].tolist()
# print(indexs)
zero_H = np.zeros_like(row_pixels)
indexs_1 = find_continuous_groups_indices(row_pixels,1)
zero_H[indexs_1] = 1
zero_img[row] = zero_H
indexs_2 = find_continuous_groups_indices(row_pixels, 2)
zero_H[indexs_2] = 2
zero_img[row] = zero_H
indexs_3 = find_continuous_groups_indices(row_pixels, 3)
zero_H[indexs_3] = 3
zero_img[row] = zero_H
indexs_4 = find_continuous_groups_indices(row_pixels, 4)
zero_H[indexs_4] = 4
zero_img[row] = zero_H
cv2.imwrite(savePath, zero_img)
# return zero_img
if __name__ == '__main__':
image_path = r'E:\BaiduNetdiskDownload\test\mydata\annotations1'
savePath = r'E:\BaiduNetdiskDownload\test\mydata\ann'
row_pixels = extract_row_pixels(image_path,savePath)
2)将线转为inline.txt文件
import numpy as np
from PIL import Image
import os
#
'''
将json线转为 训练的 点集 .lane.txt
-14.0619 510 20.1439 500 53.7171 490 87.2903 480 121.823 470 155.396 460 189.928 450 223.501 440
'''
def extract_lane_positions(label_path, culane_row_anchor, output_file):
# 打开标签图像
label = Image.open(label_path)
w, h = label.size
# 映射行采样点到图像的实际高度
# sample_tmp = [int((x * h) / 288) for x in culane_row_anchor]
sample_tmp = culane_row_anchor
lane1 = []
lane2 =[]
lane3=[]
lane4=[]
# 遍历每一个行锚框
for i, r in enumerate(sample_tmp):
# 拿到每一行
label_r = np.asarray(label)[int(round(r))]
for lane_idx in range(1, 5):
# 找出当前行中等于 1 2 3 4 的像素位置
pos = np.where(label_r == lane_idx)[0]
if len(pos) == 0:
continue
elif lane_idx ==1:
lane1.append(pos.item())
lane1.append(r)
elif lane_idx ==2:
lane2.append(pos.item())
lane2.append(r)
elif lane_idx ==3:
lane3.append(pos.item())
lane3.append(r)
elif lane_idx == 4:
lane4.append(pos.item())
lane4.append(r)
# 将提取的位置信息写入文件
lanes = [lane1, lane2, lane3, lane4]
# Open the file in write mode
with open(output_file, 'w') as f:
# Iterate over each lane list
for lane in lanes:
# Convert each element in the lane list to a string and write to the file
for i in lane:
f.write(str(i)+ ' ')
# Add a blank line to separate lanes in the file
f.write('\n')
print(f"Data written to {output_file} successfully.")
# 设置标签图像文件夹路径(labelme标注的线转为 )和输出文件夹路径
label_folder = r'E:\BaiduNetdiskDownload\test\mydata\ann'
output_folder = r'E:\BaiduNetdiskDownload\test\mydata\txt'
# 获取标签图像文件夹中所有图像文件
label_files = os.listdir(label_folder)
# 遍历每个标签图像文件,并进行位置信息提取
for label_file in label_files:
label_path = os.path.join(label_folder, label_file)
output_file = os.path.join(output_folder, label_file.split('.')[0] + '.line.txt')
# 定义行采样点(示例)
culane_row_anchor = [250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590] # 根据需要调整
# 调用函数进行位置信息提取并保存到输出文件
extract_lane_positions(label_path, culane_row_anchor, output_file)
2.生成train_gt.txt文件
import os
import numpy as np
from PIL import Image
'''
构建训练的 train_gt.txt
/driver_23_30frame/05151649_0422.MP4/00180.jpg /laneseg_label_w16/driver_23_30frame/05151649_0422.MP4/00180.png 1 1 1 1
'''
images_folder_path = r'E:\BaiduNetdiskDownload\test\mydata\XF'
label_folder_path = r'E:\BaiduNetdiskDownload\test\mydata\annotations1'
gt_file_path = r'E:\BaiduNetdiskDownload\test\mydata\train_gt.txt'
# 获取标签图像文件夹中的所有图像文件路径
label_files = [os.path.join(label_folder_path, f) for f in os.listdir(label_folder_path) if f.endswith('.png')]
image_files = [os.path.join(images_folder_path, f) for f in os.listdir(images_folder_path) if f.endswith('.jpg')]
lines = ""
for image_path in image_files:
# 构建当前图像对应的标签路径
label_file = os.path.basename(image_path).replace('.jpg', '.png')
label_path = os.path.join(label_folder_path, label_file)
# 打开标签图像
label = Image.open(label_path)
label_data = np.asarray(label)
# 获取图像中的唯一像素值(类别)
unique_values = np.unique(label_data)
# 构建当前图像的信息行
line = "/" + "images"+'/'+ f"{label_file.split('.',1)[0]+ '.jpg'}" + ' '+"/" + "annotations"+'/'+ f"{label_file}"
# line = image_path + ' ' + label_path
# 检查每个类别是否在图像中出现,1表示存在,0表示不存在
for i in range(1, 5): # 假设需要检查类别 1 到 4
if i in unique_values:
line = line + ' 1'
else:
line = line + ' 0'
# 将当前图像信息行添加到总体字符串中
lines = lines + line + '\n'
# 将信息写入输出文件
with open(gt_file_path, 'w') as f:
f.write(lines)
print(f"生成的图像信息文件已保存到 {gt_file_path}。")
3.可视化点
from PIL import Image, ImageDraw
import os
'''
将cul数据集 点集可视化
'''
def read_points_from_txt(filename):
points = []
with open(filename, 'r') as file:
lines = file.readlines()
for line in lines:
coords = line.split()
for i in range(0, len(coords)-1, 2):
x = float(coords[i])
y = float(coords[i+1])
points.append((x, y))
return points
def draw_points_on_image(points, image_path, output_path):
# 打开图像
img = Image.open(image_path)
draw = ImageDraw.Draw(img)
# 绘制点
radius = 5 # 点的半径
for (x, y) in points:
x = int(x) # 将坐标转换为整数
y = int(y)
draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill='red')
# 保存绘制后的图像
img.save(output_path)
def batch_process_points(points_folder, images_folder, output_folder):
# 获取点集文件夹中的所有文件
point_files = [f for f in os.listdir(points_folder) if f.endswith('.txt')]
for point_file in point_files:
points_path = os.path.join(points_folder, point_file)
image_name = point_file.split('.')[0] + '.jpg'
image_path = os.path.join(images_folder, image_name)
output_path = os.path.join(output_folder, image_name)
# 从文本文件中读取点
points = read_points_from_txt(points_path)
# 绘制点到图像
draw_points_on_image(points, image_path, output_path)
print(f"Processed: {image_name}")
# 设置文件夹路径
points_folder = r'E:\BaiduNetdiskDownload\test\tt\txt' # 输入点集txt
images_folder = r'E:\BaiduNetdiskDownload\test\tt\img' # 输入图像路径
output_folder = r'E:\BaiduNetdiskDownload\test\tt' # 输入保存路径
# 批量处理点集文件并绘制点到图像
batch_process_points(points_folder, images_folder, output_folder)