Jiqing Expressway数据集(IMG:image(尺寸(1080 * 1920)),GT:line_txt)
目的:处理成统一尺寸,便于model train.
(基于车道线的消失点裁剪后resize成800 * 320,GT格式包括mask,点格式的line_txt)
步骤1:解析视频
# 视频分解图片
# 1 load 2 info 3 parse 4 imshow imwrite
import cv2
import os
import glob
# 获取一个视频打开cap 参数1 file name
#cap = cv2.VideoCapture("1.mp4")
#cv2.VideoCapture(0, cv2.CAP_DSHOW) # 摄像头截取
MOV_dir="/Lane Dataset/Jiqing Expressway Video"
dir='/jing/Lane Dataset/Jingqing_pic'
MOV = glob.glob(f"{MOV_dir}/*.MOV")
for data in MOV:
MOV_name = data.split('/')[-1][:-4]
png_dir = os.path.join(dir,MOV_name)
print(png_dir)
cap = cv2.VideoCapture(data)
isOpened = cap.isOpened # 判断是否打开‘
print(isOpened)
# 获取信息 宽高
n_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print('总帧数:',n_frame) # 整个视频的总帧数
fps = cap.get(cv2.CAP_PROP_FPS) # 帧率 每秒展示多少张图片
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # w
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # h
print('帧数、宽度、高度分别为:',fps,width,height) # 帧率 宽 高
i = 0 # 记录读取多少帧
frameFrequency = 30 # 每frameFrequency保存一张图片
while(isOpened):
# 结束标志是否读取到最后一帧
if i == n_frame:
break
else:
i = i+1
(flag,frame) = cap.read() # read方法 读取每一张 flag是否读取成功 frame 读取内容
fileName = str(i+1)+'.png' # 名字累加
# True表示读取成功 进行·写入
# if 判断需要有冒号
#if flag == True:
outPutDirName = png_dir # 设置保存路径
if not os.path.exists(outPutDirName):
# 如果文件目录不存在则创建目录
os.makedirs(outPutDirName)
if i % frameFrequency == 0:
print(fileName)
cv2.imwrite(os.path.join(outPutDirName,fileName),frame,[cv2.IMWRITE_JPEG_QUALITY,100])# 质量控制 100最高
print('end!')
步骤2:crop and resize
import re
import json
import cv2
import os
import numpy as np
import glob
if __name__ == '__main__':
path="/jing/Lane Dataset/Jingqing_pic"
fileHandler_txt = "/jing/Lane Dataset/Lane_Parameters"
save_mask_dir = '/merge/jing/mask'
image_dir="/merge/jing/image"
n_0 =0
for image_path in os.listdir(path):
data_root = os.path.join(path, image_path)
image = glob.glob(f"{data_root}/*.png")
for IMG in image:
txt_path=os.path.join(fileHandler_txt,image_path[4:])
txt = os.path.join(txt_path,IMG.split('/')[-1][:-4]+".txt")
img = cv2.imread(IMG)
h = img.shape[0]
w = img.shape[1]
with open (txt) as rd:
f=rd.read()
if f=="":
continue
instane_gap = 30
thickness = w // 128
mask = np.zeros([h,w,3],dtype=np.uint8)
resultdic = {
"camera_id": 8272,
"info": {
"height": 1080 ,
"width": 1920,
"date": "2020-11-24",
"image_path": "0_Road014_Trim005_frames/XXXXXX.jpg"
},
"annotations": {}
}
fileHandler = open(txt, "r")
# Get list of all lines in file
listOfLines = fileHandler.readlines()
# Close file
fileHandler.close()
i = 0
result = []
for line in listOfLines:
i = i + 1
tmep = {
"id": i,
"lane_id": i,
"attribute": i,
"occlusion": 0,
"points": []
}
dataline = line.strip().split(": ")
redataline = re.findall(re.compile(r'[(](.*?)[)]', re.S), str(dataline))
jamp0 = []
for one in redataline:
jamp1 = []
jamp1.append(one.split(",")[0])
jamp1.append(one.split(",")[1])
jamp0.append(jamp1)
tmep['points'] = jamp0
result.append(tmep)
resultdic['annotations'] = {"lane":result}
label_info = resultdic['annotations']
len_num= len(str(n_0))
split_0= 8-len_num
Public_name ="0000000000000000000000000000000000000000000000000000000000000000"
split_name=Public_name[0:split_0]
file_name = 'jing' + "_" +split_name+str(n_0)
img_path = image_dir
for index, line in enumerate(label_info['lane']):
points_x = []
points_y = []
for point in line['points']:
points_x.append(int(float(point[0])))
points_y.append(int(float(point[1])))
ptStart = 0
ptEnd = 1
points = list(zip(points_x, points_y))
sorted(points , key=lambda k: (k[1], k[0]))
while ptEnd < len(points_x):
mask = cv2.line(mask, points[ptStart], points[ptEnd], [(index+1)*instane_gap]*3, thickness, lineType = 8)
ptStart += 1
ptEnd += 1
cv2.imencode('.png',mask)[1].tofile('{}/{}.png'.format(save_mask_dir,file_name))
ori_image= img
mask_path= save_mask_dir
mask = cv2.imread(os.path.join(save_mask_dir,file_name+'.png'))
Num = np.amax(mask[:, :, 0], axis=0)
dice = np.argmax(mask[:, :, 0], axis=0)
used_dice = []
for i in range(0, len(dice)):
if dice[i] != 0:
used_dice.append(dice[i])
if len(used_dice) == 0:
used_dice.append(0)
crop_y = np.amin(used_dice)
# print(crop_y)
img = np.zeros((mask.shape[0] - crop_y, mask.shape[1], 3), np.uint8)
img[:mask.shape[0] - crop_y, :, :] = ori_image[crop_y:, ...]
mas = np.zeros((mask.shape[0] - crop_y, mask.shape[1], 3), np.uint8)
mas[:mask.shape[0] - crop_y, :, :] = mask[crop_y:, ...]
img_new = cv2.resize(img, (800, 320), interpolation=1)
mas_new = cv2.resize(mas, (800, 320), interpolation=1)
mas_new = np.where(mas_new > 0, 255, 0)
image_name= file_name+".png"
mask_name= file_name+".png"
cv2.imwrite(os.path.join(img_path, image_name), img_new)
cv2.imwrite(os.path.join(mask_path, mask_name), mas_new)
n_0=n_0+1