{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-12-02T08:45:25.467806Z","iopub.execute_input":"2021-12-02T08:45:25.468202Z","iopub.status.idle":"2021-12-02T08:45:37.465271Z","shell.execute_reply.started":"2021-12-02T08:45:25.468094Z","shell.execute_reply":"2021-12-02T08:45:37.462018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"导入库","metadata":{}},{"cell_type":"code","source":"import numpy as np\nfrom tqdm.notebook import tqdm\ntqdm.pandas()\nimport pandas as pd\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport glob\nimport shutil\nimport sys\nsys.path.append('../input/tensorflow-great-barrier-reef')\nimport torch\nfrom PIL import Image\nimport ast","metadata":{"execution":{"iopub.status.busy":"2021-12-02T08:45:37.466812Z","iopub.execute_input":"2021-12-02T08:45:37.467151Z","iopub.status.idle":"2021-12-02T08:45:38.019662Z","shell.execute_reply.started":"2021-12-02T08:45:37.467116Z","shell.execute_reply":"2021-12-02T08:45:38.018616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"📌要点\n人们必须使用提供的python时间序列API提交预测，这使得这次竞赛不同于以前的对象检测竞赛。\n每个预测行需要包括图像的所有边界框。\n提交是格式似乎也是COCO，意思是[x_min，y_min，宽度，高度]\n混合度量F2容忍一些假阳性(FP)，以确保很少海星被遗漏。这意味着处理假阴性比假阳性更重要。\n𝐹2=5⋅𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛⋅𝑟𝑒𝑐𝑎𝑙𝑙4⋅𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛+𝑟𝑒𝑐𝑎𝑙𝑙","metadata":{}},{"cell_type":"markdown","source":"元数据\ntrain_images/ -包含视频{video_id}/{video_frame}形式的训练集照片的文件夹。\n\n[培训/测试]。图像的元数据。与其他测试文件一样，大多数测试元数据数据仅在提交后才可用于您的笔记本。只有前几行可供下载。\n\nvideo_id -图像所属视频的id号。视频id没有被有意义地排序。\n\n视频_帧-视频中图像的帧数。当潜水员浮出水面时，预计会看到帧号中偶尔出现的间隙。\n\n给定视频的无间隙子集的序列标识。序列号没有有意义地排序。\n\n序列帧-给定序列中的帧号。\n\nimage_id -图像的识别码，格式为{video_id}-{video_frame}\n\n注释——字符串格式的任何海星检测的边界框，可以用Python直接计算。不使用与您将提交的预测相同的格式。在test.csv中不可用。边界框由它在图像中左下角的像素坐标(x_min，y_min)以及它的宽度和高度(以像素为单位)来描述-->(COCO格式)","metadata":{}},{"cell_type":"code","source":"ROOT_DIR  = '/kaggle/input/tensorflow-great-barrier-reef/'\nCKPT_PATH = '/kaggle/input/greatbarrierreef-yolov5-train-ds/yolov5/runs/train/exp/weights/best.pt'\nIMG_SIZE  = 1280\nCONF      = 0.15\nIOU       = 0.50\nAUGMENT   = False","metadata":{"execution":{"iopub.status.busy":"2021-12-02T08:45:38.020740Z","iopub.execute_input":"2021-12-02T08:45:38.020969Z","iopub.status.idle":"2021-12-02T08:45:38.028105Z","shell.execute_reply.started":"2021-12-02T08:45:38.020939Z","shell.execute_reply":"2021-12-02T08:45:38.027053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-02T08:45:38.031270Z","iopub.execute_input":"2021-12-02T08:45:38.031829Z","iopub.status.idle":"2021-12-02T08:45:38.038893Z","shell.execute_reply.started":"2021-12-02T08:45:38.031781Z","shell.execute_reply":"2021-12-02T08:45:38.037780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train Data\ndf = 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-02T08:45:38.040323Z","iopub.execute_input":"2021-12-02T08:45:38.040569Z","iopub.status.idle":"2021-12-02T08:45:54.835500Z","shell.execute_reply.started":"2021-12-02T08:45:38.040542Z","shell.execute_reply":"2021-12-02T08:45:54.834665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"BBoxes的数量","metadata":{}},{"cell_type":"code","source":"df['num_bbox'] = df['annotations'].progress_apply(lambda x: len(x))\ndata = (df.num_bbox>0).value_counts()/len(df)*100\nprint(f\"No BBox: {data[0]:0.2f}% | With BBox: {data[1]:0.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2021-12-02T08:45:54.836636Z","iopub.execute_input":"2021-12-02T08:45:54.836854Z","iopub.status.idle":"2021-12-02T08:45:54.914319Z","shell.execute_reply.started":"2021-12-02T08:45:54.836825Z","shell.execute_reply":"2021-12-02T08:45:54.913150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"助手","metadata":{}},{"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-02T08:45:54.916290Z","iopub.execute_input":"2021-12-02T08:45:54.916609Z","iopub.status.idle":"2021-12-02T08:45:54.950912Z","shell.execute_reply.started":"2021-12-02T08:45:54.916566Z","shell.execute_reply":"2021-12-02T08:45:54.950022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"约洛夫5号","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-02T08:45:54.952318Z","iopub.execute_input":"2021-12-02T08:45:54.953198Z","iopub.status.idle":"2021-12-02T08:45:56.535293Z","shell.execute_reply.started":"2021-12-02T08:45:54.953159Z","shell.execute_reply":"2021-12-02T08:45:56.534096Z"},"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-02T08:45:56.537111Z","iopub.execute_input":"2021-12-02T08:45:56.537345Z","iopub.status.idle":"2021-12-02T08:45:56.543060Z","shell.execute_reply.started":"2021-12-02T08:45:56.537317Z","shell.execute_reply":"2021-12-02T08:45:56.542241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Inference","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-02T08:45:56.546104Z","iopub.execute_input":"2021-12-02T08:45:56.547116Z","iopub.status.idle":"2021-12-02T08:45:56.557964Z","shell.execute_reply.started":"2021-12-02T08:45:56.547067Z","shell.execute_reply":"2021-12-02T08:45:56.557290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-02T08:45:56.559332Z","iopub.execute_input":"2021-12-02T08:45:56.560103Z","iopub.status.idle":"2021-12-02T08:46:01.924158Z","shell.execute_reply.started":"2021-12-02T08:45:56.560053Z","shell.execute_reply":"2021-12-02T08:46:01.923205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"初始化环境","metadata":{}},{"cell_type":"code","source":"import greatbarrierreef\nenv = greatbarrierreef.make_env()# initialize the environment\niter_test = env.iter_test()      # an iterator which loops over the test set and sample submission","metadata":{"execution":{"iopub.status.busy":"2021-12-02T08:46:01.925669Z","iopub.execute_input":"2021-12-02T08:46:01.925918Z","iopub.status.idle":"2021-12-02T08:46:01.944589Z","shell.execute_reply.started":"2021-12-02T08:46:01.925885Z","shell.execute_reply":"2021-12-02T08:46:01.943475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Run Inference on Test","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-02T08:46:01.946333Z","iopub.execute_input":"2021-12-02T08:46:01.947103Z","iopub.status.idle":"2021-12-02T08:46:05.722738Z","shell.execute_reply.started":"2021-12-02T08:46:01.947057Z","shell.execute_reply":"2021-12-02T08:46:05.721750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Check Submission","metadata":{}},{"cell_type":"code","source":"sub_df = pd.read_csv('submission.csv')\nsub_df.head()","metadata":{"execution":{"iopub.status.busy":"2021-12-02T08:46:05.724045Z","iopub.execute_input":"2021-12-02T08:46:05.724269Z","iopub.status.idle":"2021-12-02T08:46:05.737132Z","shell.execute_reply.started":"2021-12-02T08:46:05.724235Z","shell.execute_reply":"2021-12-02T08:46:05.736276Z"},"trusted":true},"execution_count":null,"outputs":[]}]}