{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## 安装库","metadata":{}},{"cell_type":"code","source":"!pip install -q imagesize\n!pip install -qU wandb\n!add-apt-repository ppa:ubuntu-toolchain-r/test -y\n!apt-get update\n!apt-get upgrade libstdc++6 -y","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:50:10.484933Z","iopub.execute_input":"2021-12-08T07:50:10.485392Z","iopub.status.idle":"2021-12-08T07:50:42.191146Z","shell.execute_reply.started":"2021-12-08T07:50:10.485356Z","shell.execute_reply":"2021-12-08T07:50:42.189712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 导入库","metadata":{}},{"cell_type":"code","source":"from itertools import groupby\nimport numpy as np\nfrom tqdm.notebook import tqdm\ntqdm.pandas()\nimport pandas as pd\nimport os\nimport pickle\nimport cv2\nfrom multiprocessing import Pool\nimport matplotlib.pyplot as plt\n# import cupy as cp\nimport ast\nimport glob\n\nimport shutil\nimport sys\nsys.path.append('../input/tensorflow-great-barrier-reef')\n\nfrom joblib import Parallel, delayed\nimport imagesize","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:50:42.193355Z","iopub.execute_input":"2021-12-08T07:50:42.193629Z","iopub.status.idle":"2021-12-08T07:50:42.202898Z","shell.execute_reply.started":"2021-12-08T07:50:42.193595Z","shell.execute_reply":"2021-12-08T07:50:42.202150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom PIL import Image\nFOLD      = 6 # which fold to train\nREMOVE_NOBBOX = True # remove images with no bbox\nROOT_DIR  = '/kaggle/input/tensorflow-great-barrier-reef/'\nCKPT_PATH = '/kaggle/input/greatbarrierreef-yolov5-train-ds/yolov5/runs/train/exp/weights/best.pt'\nIMAGE_DIR = '/kaggle/images' # directory to save images\nLABEL_DIR = '/kaggle/labels' # directory to save labels","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:50:42.204338Z","iopub.execute_input":"2021-12-08T07:50:42.204661Z","iopub.status.idle":"2021-12-08T07:50:42.214777Z","shell.execute_reply.started":"2021-12-08T07:50:42.204625Z","shell.execute_reply":"2021-12-08T07:50:42.213808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE  = 1280\nCONF      = 0.15\nIOU       = 0.50\nAUGMENT   = False","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:50:42.215998Z","iopub.execute_input":"2021-12-08T07:50:42.216223Z","iopub.status.idle":"2021-12-08T07:50:42.228395Z","shell.execute_reply.started":"2021-12-08T07:50:42.216196Z","shell.execute_reply":"2021-12-08T07:50:42.227657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 创建目录","metadata":{}},{"cell_type":"code","source":"!mkdir -p {IMAGE_DIR}\n!mkdir -p {LABEL_DIR}","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:50:42.230685Z","iopub.execute_input":"2021-12-08T07:50:42.231099Z","iopub.status.idle":"2021-12-08T07:50:43.774638Z","shell.execute_reply.started":"2021-12-08T07:50:42.231063Z","shell.execute_reply":"2021-12-08T07:50:43.773088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 得到的路径","metadata":{}},{"cell_type":"code","source":"def get_path(row):\n    row['old_image_path'] = f'{ROOT_DIR}/train_images/video_{row.video_id}/{row.video_frame}.jpg'\n    row['image_path'] = f'{IMAGE_DIR}/video_{row.video_id}_{row.video_frame}.jpg'\n    row['label_path'] = f'{LABEL_DIR}/video_{row.video_id}_{row.video_frame}.txt'\n    return row","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:50:43.776395Z","iopub.execute_input":"2021-12-08T07:50:43.776669Z","iopub.status.idle":"2021-12-08T07:50:43.782820Z","shell.execute_reply.started":"2021-12-08T07:50:43.776635Z","shell.execute_reply":"2021-12-08T07:50:43.781926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 训练数据","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(f'{ROOT_DIR}/train.csv')\ndf = df.progress_apply(get_path, axis=1)\ndf['annotations'] = df['annotations'].progress_apply(lambda x: ast.literal_eval(x))\ndisplay(df.head(2))","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:50:43.784508Z","iopub.execute_input":"2021-12-08T07:50:43.785048Z","iopub.status.idle":"2021-12-08T07:51:30.237899Z","shell.execute_reply.started":"2021-12-08T07:50:43.784958Z","shell.execute_reply":"2021-12-08T07:51:30.236836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## BBoxes数量\n> 近80%的图像没有任何bbox。","metadata":{}},{"cell_type":"code","source":"df['num_bbox'] = df['annotations'].progress_apply(lambda x: len(x))\ndata = (df.num_bbox>0).value_counts(normalize=True)*100\nprint(f\"No BBox: {data[0]:0.2f}% | With BBox: {data[1]:0.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:51:30.239471Z","iopub.execute_input":"2021-12-08T07:51:30.239736Z","iopub.status.idle":"2021-12-08T07:51:30.346317Z","shell.execute_reply.started":"2021-12-08T07:51:30.239704Z","shell.execute_reply":"2021-12-08T07:51:30.345373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 清理数据","metadata":{}},{"cell_type":"code","source":"if REMOVE_NOBBOX:\n    df = df.query(\"num_bbox>0\")","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:51:30.348208Z","iopub.execute_input":"2021-12-08T07:51:30.348865Z","iopub.status.idle":"2021-12-08T07:51:30.376483Z","shell.execute_reply.started":"2021-12-08T07:51:30.348816Z","shell.execute_reply":"2021-12-08T07:51:30.375574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 写图片","metadata":{}},{"cell_type":"code","source":"def make_copy(path):\n    data = path.split('/')\n    filename = data[-1]\n    video_id = data[-2]\n    new_path = os.path.join(IMAGE_DIR,f'{video_id}_{filename}')\n    shutil.copy(path, new_path)\n    return","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:51:30.378035Z","iopub.execute_input":"2021-12-08T07:51:30.378296Z","iopub.status.idle":"2021-12-08T07:51:30.385119Z","shell.execute_reply.started":"2021-12-08T07:51:30.378265Z","shell.execute_reply":"2021-12-08T07:51:30.383048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_paths = df.old_image_path.tolist()\n_ = Parallel(n_jobs=-1, backend='threading')(delayed(make_copy)(path) for path in tqdm(image_paths))","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:51:30.386765Z","iopub.execute_input":"2021-12-08T07:51:30.387633Z","iopub.status.idle":"2021-12-08T07:52:02.060335Z","shell.execute_reply.started":"2021-12-08T07:51:30.387585Z","shell.execute_reply":"2021-12-08T07:52:02.059394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 编写函数","metadata":{}},{"cell_type":"code","source":"def voc2yolo(image_height, image_width, bboxes):\n    \"\"\"\n    voc  => [x1, y1, x2, y1]\n    yolo => [xmid, ymid, w, h] (normalized)\n    \"\"\"\n    \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]/ image_height\n    \n    w = bboxes[..., 2] - bboxes[..., 0]\n    h = bboxes[..., 3] - bboxes[..., 1]\n    \n    bboxes[..., 0] = bboxes[..., 0] + w/2\n    bboxes[..., 1] = bboxes[..., 1] + h/2\n    bboxes[..., 2] = w\n    bboxes[..., 3] = h\n    \n    return bboxes\n\ndef yolo2voc(image_height, image_width, bboxes):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    voc  => [x1, y1, x2, y1]\n    \n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]* image_height\n    \n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n    \n    return bboxes\n\ndef coco2yolo(image_height, image_width, bboxes):\n    \"\"\"\n    coco => [xmin, ymin, w, h]\n    yolo => [xmid, ymid, w, h] (normalized)\n    \"\"\"\n    \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    # normolizinig\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]/ image_height\n    \n    # converstion (xmin, ymin) => (xmid, ymid)\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]/2\n    \n    return bboxes\n\ndef yolo2coco(image_height, image_width, bboxes):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    coco => [xmin, ymin, w, h]\n    \n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    # denormalizing\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]* image_height\n    \n    # converstion (xmid, ymid) => (xmin, ymin) \n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    \n    return bboxes\n\ndef load_image(image_path):\n    return cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\n\n\ndef plot_one_box(x, img, color=None, label=None, line_thickness=None):\n    # Plots one bounding box on image img\n    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness\n    color = color or [random.randint(0, 255) for _ in range(3)]\n    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n    if label:\n        tf = max(tl - 1, 1)  # font thickness\n        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled\n        cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n\ndef draw_bboxes(img, bboxes, classes, class_ids, colors = None, show_classes = None, bbox_format = 'yolo', class_name = False, line_thickness = 2):  \n     \n    image = img.copy()\n    show_classes = classes if show_classes is None else show_classes\n    colors = (0, 255 ,0) if colors is None else colors\n    \n    if bbox_format == 'yolo':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes:\n            \n                x1 = round(float(bbox[0])*image.shape[1])\n                y1 = round(float(bbox[1])*image.shape[0])\n                w  = round(float(bbox[2])*image.shape[1]/2) #w/2 \n                h  = round(float(bbox[3])*image.shape[0]/2)\n\n                voc_bbox = (x1-w, y1-h, x1+w, y1+h)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(get_label(cls)),\n                             line_thickness = line_thickness)\n            \n    elif bbox_format == 'coco':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes:            \n                x1 = int(round(bbox[0]))\n                y1 = int(round(bbox[1]))\n                w  = int(round(bbox[2]))\n                h  = int(round(bbox[3]))\n\n                voc_bbox = (x1, y1, x1+w, y1+h)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(cls_id),\n                             line_thickness = line_thickness)\n\n    elif bbox_format == 'voc_pascal':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes: \n                x1 = int(round(bbox[0]))\n                y1 = int(round(bbox[1]))\n                x2 = int(round(bbox[2]))\n                y2 = int(round(bbox[3]))\n                voc_bbox = (x1, y1, x2, y2)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(cls_id),\n                             line_thickness = line_thickness)\n    else:\n        raise ValueError('wrong bbox format')\n\n    return image\n\ndef get_bbox(annots):\n    bboxes = [list(annot.values()) for annot in annots]\n    return bboxes\n\ndef get_imgsize(row):\n    row['width'], row['height'] = imagesize.get(row['image_path'])\n    return row\n\nnp.random.seed(32)\ncolors = [(np.random.randint(255), np.random.randint(255), np.random.randint(255))\\\n          for idx in range(1)]","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:02.062555Z","iopub.execute_input":"2021-12-08T07:52:02.062946Z","iopub.status.idle":"2021-12-08T07:52:02.115652Z","shell.execute_reply.started":"2021-12-08T07:52:02.062892Z","shell.execute_reply":"2021-12-08T07:52:02.114793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 创建BBox","metadata":{}},{"cell_type":"code","source":"df['bboxes'] = df.annotations.progress_apply(get_bbox)\ndf.head(2)","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:02.117269Z","iopub.execute_input":"2021-12-08T07:52:02.118322Z","iopub.status.idle":"2021-12-08T07:52:04.998757Z","shell.execute_reply.started":"2021-12-08T07:52:02.118271Z","shell.execute_reply":"2021-12-08T07:52:04.997774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 得到图像大小","metadata":{}},{"cell_type":"code","source":"df = df.progress_apply(get_imgsize,axis=1)\ndisplay(df.width.unique(), df.height.unique())\ndisplay(df.head(2))","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:05.002227Z","iopub.execute_input":"2021-12-08T07:52:05.002570Z","iopub.status.idle":"2021-12-08T07:52:11.974773Z","shell.execute_reply.started":"2021-12-08T07:52:05.002533Z","shell.execute_reply":"2021-12-08T07:52:11.973401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 创建标签","metadata":{}},{"cell_type":"code","source":"cnt = 0\nall_bboxes = []\nfor row_idx in tqdm(range(df.shape[0])):\n    row = df.iloc[row_idx]\n    image_height = row.height\n    image_width  = row.width\n    bboxes_coco  = np.array(row.bboxes).astype(np.float32).copy()\n    num_bbox     = len(bboxes_coco)\n    names        = ['cots']*num_bbox\n    labels       = [0]*num_bbox\n    ## Create Annotation(YOLO)\n    with open(row.label_path, 'w') as f:\n        if num_bbox<1:\n            annot = ''\n            f.write(annot)\n            cnt+=1\n            continue\n        bboxes_yolo  = coco2yolo(image_height, image_width, bboxes_coco)\n        bboxes_yolo  = np.clip(bboxes_yolo, 0, 1)\n        all_bboxes.extend(bboxes_yolo)\n        for bbox_idx in range(len(bboxes_yolo)):\n            annot = [str(labels[bbox_idx])]+ list(bboxes_yolo[bbox_idx].astype(str))+(['\\n'] if num_bbox!=(bbox_idx+1) else [''])\n            annot = ' '.join(annot)\n            annot = annot.strip(' ')\n            f.write(annot)\nprint('Missing:',cnt)","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:11.976496Z","iopub.execute_input":"2021-12-08T07:52:11.976853Z","iopub.status.idle":"2021-12-08T07:52:15.097818Z","shell.execute_reply.started":"2021-12-08T07:52:11.976807Z","shell.execute_reply":"2021-12-08T07:52:15.096935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## BBox分布","metadata":{}},{"cell_type":"markdown","source":"## x_center Vs y_center","metadata":{}},{"cell_type":"code","source":"from scipy.stats import gaussian_kde\n\nall_bboxes = np.array(all_bboxes)\n\nx_val = all_bboxes[...,0]\ny_val = all_bboxes[...,1]\n\n# Calculate the point density\nxy = np.vstack([x_val,y_val])\nz = gaussian_kde(xy)(xy)\n\nfig, ax = plt.subplots(figsize = (10, 10))\nax.axis('off')\nax.scatter(x_val, y_val, c=z, s=100, cmap='viridis')\n# ax.set_xlabel('x_mid')\n# ax.set_ylabel('y_mid')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:15.099437Z","iopub.execute_input":"2021-12-08T07:52:15.100335Z","iopub.status.idle":"2021-12-08T07:52:17.641697Z","shell.execute_reply.started":"2021-12-08T07:52:15.100239Z","shell.execute_reply":"2021-12-08T07:52:17.638253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## `width` Vs `height`","metadata":{}},{"cell_type":"code","source":"x_val = all_bboxes[...,2]\ny_val = all_bboxes[...,3]\n\n# Calculate the point density\nxy = np.vstack([x_val,y_val])\nz = gaussian_kde(xy)(xy)\n\nfig, ax = plt.subplots(figsize = (10, 10))\nax.axis('off')\nax.scatter(x_val, y_val, c=z, s=100, cmap='viridis')\n# ax.set_xlabel('bbox_width')\n# ax.set_ylabel('bbox_height')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:17.643610Z","iopub.execute_input":"2021-12-08T07:52:17.644219Z","iopub.status.idle":"2021-12-08T07:52:20.086257Z","shell.execute_reply.started":"2021-12-08T07:52:17.644165Z","shell.execute_reply":"2021-12-08T07:52:20.084899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Area","metadata":{}},{"cell_type":"code","source":"import seaborn as sns\nsns.set(style='white')\nareas = all_bboxes[...,2]*all_bboxes[...,3]*720*1280\nplt.figure(figsize=(12,8))\nsns.kdeplot(areas,shade=True,palette='viridis')\nplt.axis('OFF')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:20.087632Z","iopub.execute_input":"2021-12-08T07:52:20.087903Z","iopub.status.idle":"2021-12-08T07:52:20.378650Z","shell.execute_reply.started":"2021-12-08T07:52:20.087871Z","shell.execute_reply":"2021-12-08T07:52:20.377578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 可视化","metadata":{}},{"cell_type":"code","source":"df2 = df[(df.num_bbox>0)].sample(100) # takes samples with bbox\nfor idx in range(10):\n    row = df2.iloc[idx]\n    img           = load_image(row.image_path)\n    image_height  = row.height\n    image_width   = row.width\n    bboxes_coco   = np.array(row.bboxes)\n    bboxes_yolo   = coco2yolo(image_height, image_width, bboxes_coco)\n    names         = ['cots']*len(bboxes_coco)\n    labels        = [0]*len(bboxes_coco)\n\n    plt.figure(figsize = (12, 8))\n    plt.imshow(draw_bboxes(img = img,\n                           bboxes = bboxes_yolo, \n                           classes = names,\n                           class_ids = labels,\n                           class_name = True, \n                           colors = colors, \n                           bbox_format = 'yolo',\n                           line_thickness = 2))\n    plt.axis('OFF')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:20.379992Z","iopub.execute_input":"2021-12-08T07:52:20.380269Z","iopub.status.idle":"2021-12-08T07:52:25.316938Z","shell.execute_reply.started":"2021-12-08T07:52:20.380236Z","shell.execute_reply":"2021-12-08T07:52:25.316123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 创建折叠","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import GroupKFold\nkf = GroupKFold(n_splits = 10) # num_folds=3 as there are total 3 videos\ndf = df.reset_index(drop=True)\ndf['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(kf.split(df, y = df.video_id.tolist(), groups=df.sequence)):\n    df.loc[val_idx, 'fold'] = fold\ndisplay(df.fold.value_counts())","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:25.318394Z","iopub.execute_input":"2021-12-08T07:52:25.318832Z","iopub.status.idle":"2021-12-08T07:52:25.342346Z","shell.execute_reply.started":"2021-12-08T07:52:25.318794Z","shell.execute_reply":"2021-12-08T07:52:25.341410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 数据集","metadata":{}},{"cell_type":"code","source":"train_files = []\nval_files   = []\ntrain_df = df.query(\"fold!=@FOLD\")\nvalid_df = df.query(\"fold==@FOLD\")\ntrain_files += list(train_df.image_path.unique())\nval_files += list(valid_df.image_path.unique())\nlen(train_files), len(val_files)","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:25.343901Z","iopub.execute_input":"2021-12-08T07:52:25.344180Z","iopub.status.idle":"2021-12-08T07:52:25.365418Z","shell.execute_reply.started":"2021-12-08T07:52:25.344147Z","shell.execute_reply":"2021-12-08T07:52:25.364544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 配置","metadata":{}},{"cell_type":"code","source":"import yaml\n\ncwd = '/kaggle/working/'\n\nwith open(os.path.join( cwd , 'train.txt'), 'w') as f:\n    for path in train_df.image_path.tolist():\n        f.write(path+'\\n')\n            \nwith open(os.path.join(cwd , 'val.txt'), 'w') as f:\n    for path in valid_df.image_path.tolist():\n        f.write(path+'\\n')\n\ndata = dict(\n    path  = '/kaggle/working',\n    train =  os.path.join( cwd , 'train.txt') ,\n    val   =  os.path.join( cwd , 'val.txt' ),\n    nc    = 1,\n    names = ['cots'],\n    )\n\nwith open(os.path.join( cwd , 'tgbr.yaml'), 'w') as outfile:\n    yaml.dump(data, outfile, default_flow_style=False)\n\nf = open(os.path.join( cwd , 'tgbr.yaml'), 'r')\nprint('\\nyaml:')\nprint(f.read())","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:25.366707Z","iopub.execute_input":"2021-12-08T07:52:25.366992Z","iopub.status.idle":"2021-12-08T07:52:25.384013Z","shell.execute_reply.started":"2021-12-08T07:52:25.366932Z","shell.execute_reply":"2021-12-08T07:52:25.383057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 编写函数","metadata":{}},{"cell_type":"code","source":"def get_path(row):\n    row['image_path'] = f'{ROOT_DIR}/train_images/video_{row.video_id}/{row.video_frame}.jpg'\n    return row","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:25.385314Z","iopub.execute_input":"2021-12-08T07:52:25.385685Z","iopub.status.idle":"2021-12-08T07:52:25.390853Z","shell.execute_reply.started":"2021-12-08T07:52:25.385634Z","shell.execute_reply":"2021-12-08T07:52:25.389909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def voc2yolo(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    voc  => [x1, y1, x2, y1]\n    yolo => [xmid, ymid, w, h] (normalized)\n    \"\"\"\n    \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]/ image_height\n    \n    w = bboxes[..., 2] - bboxes[..., 0]\n    h = bboxes[..., 3] - bboxes[..., 1]\n    \n    bboxes[..., 0] = bboxes[..., 0] + w/2\n    bboxes[..., 1] = bboxes[..., 1] + h/2\n    bboxes[..., 2] = w\n    bboxes[..., 3] = h\n    \n    return bboxes\n\ndef yolo2voc(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    voc  => [x1, y1, x2, y1]\n    \n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]* image_height\n    \n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n    \n    return bboxes\n\ndef coco2yolo(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    coco => [xmin, ymin, w, h]\n    yolo => [xmid, ymid, w, h] (normalized)\n    \"\"\"\n    \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    # normolizinig\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]/ image_height\n    \n    # converstion (xmin, ymin) => (xmid, ymid)\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]/2\n    \n    return bboxes\n\ndef yolo2coco(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    coco => [xmin, ymin, w, h]\n    \n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    # denormalizing\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]* image_height\n    \n    # converstion (xmid, ymid) => (xmin, ymin) \n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    \n    return bboxes\n\ndef voc2coco(bboxes, image_height=720, image_width=1280):\n    bboxes  = voc2yolo(bboxes, image_height, image_width)\n    bboxes  = yolo2coco(bboxes, image_height, image_width)\n    return bboxes\n\n\ndef load_image(image_path):\n    return cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\n\n\ndef plot_one_box(x, img, color=None, label=None, line_thickness=None):\n    # Plots one bounding box on image img\n    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness\n    color = color or [random.randint(0, 255) for _ in range(3)]\n    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n    if label:\n        tf = max(tl - 1, 1)  # font thickness\n        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled\n        cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n\ndef draw_bboxes(img, bboxes, classes, class_ids, colors = None, show_classes = None, bbox_format = 'yolo', class_name = False, line_thickness = 2):  \n     \n    image = img.copy()\n    show_classes = classes if show_classes is None else show_classes\n    colors = (0, 255 ,0) if colors is None else colors\n    \n    if bbox_format == 'yolo':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes:\n            \n                x1 = round(float(bbox[0])*image.shape[1])\n                y1 = round(float(bbox[1])*image.shape[0])\n                w  = round(float(bbox[2])*image.shape[1]/2) #w/2 \n                h  = round(float(bbox[3])*image.shape[0]/2)\n\n                voc_bbox = (x1-w, y1-h, x1+w, y1+h)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(get_label(cls)),\n                             line_thickness = line_thickness)\n            \n    elif bbox_format == 'coco':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes:            \n                x1 = int(round(bbox[0]))\n                y1 = int(round(bbox[1]))\n                w  = int(round(bbox[2]))\n                h  = int(round(bbox[3]))\n\n                voc_bbox = (x1, y1, x1+w, y1+h)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(cls_id),\n                             line_thickness = line_thickness)\n\n    elif bbox_format == 'voc_pascal':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes: \n                x1 = int(round(bbox[0]))\n                y1 = int(round(bbox[1]))\n                x2 = int(round(bbox[2]))\n                y2 = int(round(bbox[3]))\n                voc_bbox = (x1, y1, x2, y2)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(cls_id),\n                             line_thickness = line_thickness)\n    else:\n        raise ValueError('wrong bbox format')\n\n    return image\n\ndef get_bbox(annots):\n    bboxes = [list(annot.values()) for annot in annots]\n    return bboxes\n\ndef get_imgsize(row):\n    row['width'], row['height'] = imagesize.get(row['image_path'])\n    return row\n\nnp.random.seed(32)\ncolors = [(np.random.randint(255), np.random.randint(255), np.random.randint(255))\\\n          for idx in range(1)]","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:25.392375Z","iopub.execute_input":"2021-12-08T07:52:25.392750Z","iopub.status.idle":"2021-12-08T07:52:25.435803Z","shell.execute_reply.started":"2021-12-08T07:52:25.392708Z","shell.execute_reply":"2021-12-08T07:52:25.435131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 建立模型","metadata":{}},{"cell_type":"code","source":"!mkdir -p /root/.config/Ultralytics\n!cp /kaggle/input/yolov5-font/Arial.ttf /root/.config/Ultralytics/","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:25.436901Z","iopub.execute_input":"2021-12-08T07:52:25.437207Z","iopub.status.idle":"2021-12-08T07:52:27.008211Z","shell.execute_reply.started":"2021-12-08T07:52:25.437175Z","shell.execute_reply":"2021-12-08T07:52:27.006907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_model(ckpt_path, conf=0.25, iou=0.50):\n    model = torch.hub.load('/kaggle/input/yolov5-lib-ds',\n                           'custom',\n                           path=ckpt_path,\n                           source='local',\n                           force_reload=True)  # local repo\n    model.conf = conf  # NMS confidence threshold\n    model.iou  = iou  # NMS IoU threshold\n    model.classes = None   # (optional list) filter by class, i.e. = [0, 15, 16] for persons, cats and dogs\n    model.multi_label = False  # NMS multiple labels per box\n    model.max_det = 1000  # maximum number of detections per image\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:27.010115Z","iopub.execute_input":"2021-12-08T07:52:27.010401Z","iopub.status.idle":"2021-12-08T07:52:27.017632Z","shell.execute_reply.started":"2021-12-08T07:52:27.010367Z","shell.execute_reply":"2021-12-08T07:52:27.016669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 编写函数","metadata":{}},{"cell_type":"code","source":"def predict(model, img, size=768, augment=False):\n    height, width = img.shape[:2]\n    results = model(img, size=size, augment=augment)  # custom inference size\n    preds   = results.pandas().xyxy[0]\n    bboxes  = preds[['xmin','ymin','xmax','ymax']].values\n    if len(bboxes):\n        bboxes  = voc2coco(bboxes,height,width).astype(int)\n        confs   = preds.confidence.values\n        return bboxes, confs\n    else:\n        return [],[]\n    \ndef format_prediction(bboxes, confs):\n    annot = ''\n    if len(bboxes)>0:\n        for idx in range(len(bboxes)):\n            xmin, ymin, w, h = bboxes[idx]\n            conf             = confs[idx]\n            annot += f'{conf} {xmin} {ymin} {w} {h}'\n            annot +=' '\n        annot = annot.strip(' ')\n    return annot\n\ndef show_img(img, bboxes, bbox_format='yolo'):\n    names  = ['starfish']*len(bboxes)\n    labels = [0]*len(bboxes)\n    img    = draw_bboxes(img = img,\n                           bboxes = bboxes, \n                           classes = names,\n                           class_ids = labels,\n                           class_name = True, \n                           colors = colors, \n                           bbox_format = bbox_format,\n                           line_thickness = 2)\n    return Image.fromarray(img).resize((800, 400))","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:27.019236Z","iopub.execute_input":"2021-12-08T07:52:27.020220Z","iopub.status.idle":"2021-12-08T07:52:27.034516Z","shell.execute_reply.started":"2021-12-08T07:52:27.020141Z","shell.execute_reply":"2021-12-08T07:52:27.033515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 在训练集上进行推理预测","metadata":{}},{"cell_type":"code","source":"model = load_model(CKPT_PATH, conf=CONF, iou=IOU)\nimage_paths = df[df.num_bbox>1].sample(100).image_path.tolist()\nfor idx, path in enumerate(image_paths):\n    img = cv2.imread(path)[...,::-1]\n    bboxes, confis = predict(model, img, size=IMG_SIZE, augment=AUGMENT)\n    display(show_img(img, bboxes, bbox_format='coco'))\n    if idx>5:\n        break","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:27.036003Z","iopub.execute_input":"2021-12-08T07:52:27.036247Z","iopub.status.idle":"2021-12-08T07:52:33.388843Z","shell.execute_reply.started":"2021-12-08T07:52:27.036219Z","shell.execute_reply":"2021-12-08T07:52:33.387811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 初始化环境","metadata":{}},{"cell_type":"code","source":"import greatbarrierreef\nenv = greatbarrierreef.make_env()# 初始化环境\niter_test = env.iter_test()      # 遍历测试集和样本提交的迭代器","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:33.390423Z","iopub.execute_input":"2021-12-08T07:52:33.390686Z","iopub.status.idle":"2021-12-08T07:52:33.418025Z","shell.execute_reply.started":"2021-12-08T07:52:33.390651Z","shell.execute_reply":"2021-12-08T07:52:33.417236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 运行测试推理","metadata":{}},{"cell_type":"code","source":"model = load_model(CKPT_PATH, conf=CONF, iou=IOU)\nfor idx, (img, pred_df) in enumerate(tqdm(iter_test)):\n    bboxes, confs  = predict(model, img, size=IMG_SIZE, augment=True)\n    annot          = format_prediction(bboxes, confs)\n    pred_df['annotations'] = annot\n    env.predict(pred_df)\n    if idx<3:\n        display(show_img(img, bboxes, bbox_format='coco'))","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:33.419168Z","iopub.execute_input":"2021-12-08T07:52:33.419798Z","iopub.status.idle":"2021-12-08T07:52:37.827210Z","shell.execute_reply.started":"2021-12-08T07:52:33.419765Z","shell.execute_reply":"2021-12-08T07:52:37.826060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 检查提交","metadata":{}},{"cell_type":"code","source":"sub_df = pd.read_csv('submission.csv')\nsub_df.head()","metadata":{"execution":{"iopub.status.busy":"2021-12-08T07:52:37.829055Z","iopub.execute_input":"2021-12-08T07:52:37.829303Z","iopub.status.idle":"2021-12-08T07:52:37.842780Z","shell.execute_reply.started":"2021-12-08T07:52:37.829271Z","shell.execute_reply":"2021-12-08T07:52:37.841739Z"},"trusted":true},"execution_count":null,"outputs":[]}]}