{"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","_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-07-05T09:30:42.787038Z","iopub.execute_input":"2023-07-05T09:30:42.787709Z","iopub.status.idle":"2023-07-05T09:30:44.572139Z","shell.execute_reply.started":"2023-07-05T09:30:42.787662Z","shell.execute_reply":"2023-07-05T09:30:44.571274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport json\nimport glob\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport os\nimport tensorflow as tf\nimport random\nfrom PIL import Image\nimport shutil\nimport wandb","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.574238Z","iopub.execute_input":"2023-07-05T09:30:44.574590Z","iopub.status.idle":"2023-07-05T09:30:44.583047Z","shell.execute_reply.started":"2023-07-05T09:30:44.574561Z","shell.execute_reply":"2023-07-05T09:30:44.582221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#!mkdir train\n#!mkdir train/images\n#!mkdir train/labels\n#!mkdir val\n#!mkdir val/images\n#!mkdir val/labels\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.584733Z","iopub.execute_input":"2023-07-05T09:30:44.585554Z","iopub.status.idle":"2023-07-05T09:30:44.591474Z","shell.execute_reply.started":"2023-07-05T09:30:44.585522Z","shell.execute_reply":"2023-07-05T09:30:44.590470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = '/kaggle/working/train/'\nval_dir = '/kaggle/working/val/'\nimg_dir = '/kaggle/input/hubmap-hacking-the-human-vasculature/train/' ","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.594500Z","iopub.execute_input":"2023-07-05T09:30:44.595199Z","iopub.status.idle":"2023-07-05T09:30:44.601201Z","shell.execute_reply.started":"2023-07-05T09:30:44.595167Z","shell.execute_reply":"2023-07-05T09:30:44.600211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images = glob.glob(\"/kaggle/input/hubmap-hacking-the-human-vasculature/train/*.tif\")\n\nprint(len(train_images))\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.602826Z","iopub.execute_input":"2023-07-05T09:30:44.603545Z","iopub.status.idle":"2023-07-05T09:30:44.638535Z","shell.execute_reply.started":"2023-07-05T09:30:44.603513Z","shell.execute_reply":"2023-07-05T09:30:44.637632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" def change_gray(img):\n     gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) #obtained了一个(512,512,1)的灰度图gray_img。\n     gray_img = cv2.equalizeHist(gray_img)            #gray_img = cv2.equalizeHist(gray_img)\n     gray_img = cv2.GaussianBlur(gray_img, (5, 5), 0) #高斯滤波:使用cv2.GaussianBlur()平滑图像,滤除噪声\n     return gray_img\n\nlabel_map = {\n                'glomerulus': 1,\n                'blood_vessel': 0,\n                'unsure': 2\n            } ","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.640498Z","iopub.execute_input":"2023-07-05T09:30:44.641173Z","iopub.status.idle":"2023-07-05T09:30:44.647365Z","shell.execute_reply.started":"2023-07-05T09:30:44.641141Z","shell.execute_reply":"2023-07-05T09:30:44.646379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_label(coords,cls,label_txt_path):\n    image_width = 512  # 图像宽度\n    image_height = 512  # 图像高度\n    yolov8_labels = []\n\n    for coord in coords:\n        # 计算中心点坐标和边界框的宽度和高度\n        x_coords = [point[0] for point in coord]\n        y_coords = [point[1] for point in coord]\n        center_x = sum(x_coords) / len(coord)\n        center_y = sum(y_coords) / len(coord)\n        width = max(x_coords) - min(x_coords)\n        height = max(y_coords) - min(y_coords)\n\n        # 标准化坐标值\n        normalized_center_x = center_x / image_width\n        normalized_center_y = center_y / image_height\n        normalized_width = width / image_width\n        normalized_height = height / image_height\n\n        # 构建YOLOv8标签字符串\n        yolo_label = \"{} {} {} {} {}\".format(cls,normalized_center_x, normalized_center_y, normalized_width,\n                                            normalized_height)\n        yolov8_labels.append(yolo_label)\n\n    with open(label_txt_path, 'a') as file:\n        for label in yolov8_labels:\n            file.write(label + '\\n')\n    #print(\"YOLOv8 labels have been written to the file:\", label_txt_path)\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.648842Z","iopub.execute_input":"2023-07-05T09:30:44.649205Z","iopub.status.idle":"2023-07-05T09:30:44.661274Z","shell.execute_reply.started":"2023-07-05T09:30:44.649175Z","shell.execute_reply":"2023-07-05T09:30:44.660337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_Seg_label(coords,cls,label_txt_path):\n    image_width = 512  # 图像宽度\n    image_height = 512  # 图像高度\n    \n    yolo_label = str(cls)  # 开始构建标签字符串\n    \n    # 逐个获取每个轮廓点组\n    for coord in coords: \n        \n        # 逐个获取每个轮廓点\n        for point in coord:\n            x = point[0]\n            y = point[1]\n            \n            # 归一化坐标\n            normalized_x = x / image_width\n            normalized_y = y / image_height\n                                 \n            # 拼接坐标\n            yolo_label += ' ' + str(normalized_x) + ' ' + str(normalized_y)  \n    \n    # 写入标签文件 \n    with open(label_txt_path, 'a') as file:\n        file.write(yolo_label + '\\n')\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.662864Z","iopub.execute_input":"2023-07-05T09:30:44.663688Z","iopub.status.idle":"2023-07-05T09:30:44.675781Z","shell.execute_reply.started":"2023-07-05T09:30:44.663655Z","shell.execute_reply":"2023-07-05T09:30:44.674929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Polygon:\n    def __init__(self, image_id, annotations):\n        self.image_id = image_id\n        self.annotations = annotations\n        \n        self.blood_vessel = [] \n        self.glomerulus = []\n        self.unsure = []\n        \n        self.parse_annotations()\n        \n    def parse_annotations(self):\n        for anno in self.annotations:\n            anno_type = anno['type']\n            coordinates = anno['coordinates']\n            \n            if anno_type == 'blood_vessel':\n                self.blood_vessel.append(coordinates)\n            elif anno_type == 'glomerulus':\n                self.glomerulus.append(coordinates)\n            elif anno_type == 'unsure':\n                self.unsure.append(coordinates)    \n    \n    @classmethod\n    def get_by_id(cls, image_id, data):\n        for polygon in data:\n            if polygon.image_id == image_id:\n                return polygon  \n        \n        return None \n    \n    @classmethod\n    def image_id_exists(cls, image_id, data):\n        for d in data:\n            if d.image_id == image_id:\n                return True\n        return False  \n    \n   \n    def visualize_draw_Original_trainImage(self):\n        image_copy = self.get_train_image()\n           \n        plt.imshow(image_copy)\n        plt.show()\n   \n     \n    def visualize_annotations_drawContours(self, color_map):\n            image_copy = self.to_gray_train_img()\n            for coordinates in self.blood_vessel: \n                image_copy = cv2.drawContours(image_copy, [np.array(coordinates)], \n                                             -1, color_map['blood_vessel'], 2)\n\n            for coordinates in self.glomerulus:\n                image_copy = cv2.drawContours(image_copy, [np.array(coordinates)], \n                                             -1, color_map['glomerulus'], 2)  \n\n            for coordinates in self.unsure:  \n                image_copy = cv2.drawContours(image_copy, [np.array(coordinates)], \n                                             -1, color_map['unsure'], 2)  \n            plt.imshow(image_copy)\n            plt.show()\n    \n    def build_YOLOFormat_images_labels(self,dir_name):\n       \n        source_file = os.path.join(img_dir, self.image_id + '.tif')\n        target_directory = os.path.join(dir_name, 'images')\n      \n        shutil.copy(source_file, target_directory)\n        #print('convert jpg',source_file)\n        label_txt_path =  os.path.join(dir_name, 'labels', self.image_id + '.txt')\n        for coordinates in self.blood_vessel:\n            make_Seg_label(coordinates,0,label_txt_path)\n        for coordinates in self.glomerulus:\n            make_Seg_label(coordinates,1,label_txt_path)\n        for coordinates in self.unsure:  \n            make_Seg_label(coordinates,2,label_txt_path)    \n    \n    \n    def to_gray_train_img(self):\n        img = self.get_train_image()\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) #obtained了一个(512,512,1)的灰度图gray_img。\n        gray_img = cv2.equalizeHist(gray_img)            #gray_img = cv2.equalizeHist(gray_img)\n        gray_img = cv2.GaussianBlur(gray_img, (5, 5), 0) #高斯滤波:使用cv2.GaussianBlur()平滑图像,滤除噪声\n        return gray_img\n            \n\n    def to_mask(self):\n        # Input is grayscale\n        img = np.zeros((512, 512, 1), dtype=np.uint8)  \n        label_map = {\n                'glomerulus': 1,\n                'blood_vessel': 2  \n            } \n        for ann in self.annotations:\n            label = ann['type']\n            coords = ann['coordinates']\n            if label == 'unsure':\n                # Ignore unsure annotations\n                continue \n            pixel_value = label_map[label]  \n            cv2.fillPoly(img, [np.array(coords)], pixel_value)\n        return img    \n           \n            \n    \n  \n    def get_train_image_by_id(self, image_id):\n        \"\"\"Get training image by image_id.\"\"\"\n        image_path = os.path.join(img_dir,f'{image_id}.tif')\n        image = cv2.imread(image_path)\n        return image\n    \n    def get_train_image(self):\n        \"\"\"Get training image by image_id.\"\"\"\n        image_path = os.path.join(img_dir,f'{self.image_id}.tif')\n        image = cv2.imread(image_path)\n        return image","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.677454Z","iopub.execute_input":"2023-07-05T09:30:44.678095Z","iopub.status.idle":"2023-07-05T09:30:44.700507Z","shell.execute_reply.started":"2023-07-05T09:30:44.678063Z","shell.execute_reply":"2023-07-05T09:30:44.699519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = []\nwith open('/kaggle/input/hubmap-hacking-the-human-vasculature/polygons.jsonl') as f:\n    for line in f:\n        obj = json.loads(line)\n        polygon = Polygon(obj['id'],obj['annotations'])\n        data.append(polygon)\n\nprint(len(data)) ","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:44.705437Z","iopub.execute_input":"2023-07-05T09:30:44.705711Z","iopub.status.idle":"2023-07-05T09:30:48.765619Z","shell.execute_reply.started":"2023-07-05T09:30:44.705688Z","shell.execute_reply":"2023-07-05T09:30:48.763772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"color_map = {\n    'blood_vessel': (0, 255, 0),  # 绿\n    'glomerulus':  (0, 0, 255),   # 蓝\n    'unsure':      (255, 0, 0)    # 红\n}\n    ","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:48.767156Z","iopub.execute_input":"2023-07-05T09:30:48.767606Z","iopub.status.idle":"2023-07-05T09:30:48.773225Z","shell.execute_reply.started":"2023-07-05T09:30:48.767570Z","shell.execute_reply":"2023-07-05T09:30:48.772206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for img_path in train_images[:20]:\n   \n    img_id = img_path.split('/')[-1].split('.')[0]\n    polygon_1 = Polygon.get_by_id(img_id,data)\n    if polygon_1 is not None: \n        polygon_1.visualize_draw_Original_trainImage()\n        polygon_1.visualize_annotations_drawContours(color_map)\n        mask = polygon_1.to_mask() \n        plt.imshow(mask)\n        plt.show()\n        \n        \n    else:\n        print(f'Cannot find image_id {img_id}') \n        \n ","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:48.774483Z","iopub.execute_input":"2023-07-05T09:30:48.775472Z","iopub.status.idle":"2023-07-05T09:30:49.703218Z","shell.execute_reply.started":"2023-07-05T09:30:48.775436Z","shell.execute_reply":"2023-07-05T09:30:49.702189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"active_train_Polygons = []\nfor img_path in train_images:\n    \n    img_id = img_path.split('/')[-1].split('.')[0]\n    if(Polygon.image_id_exists(img_id,data)):\n       \n        active_train_Polygons.append(Polygon.get_by_id(img_id, data))\n    \nprint(len(active_train_Polygons))","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:49.704660Z","iopub.execute_input":"2023-07-05T09:30:49.705486Z","iopub.status.idle":"2023-07-05T09:30:51.057208Z","shell.execute_reply.started":"2023-07-05T09:30:49.705450Z","shell.execute_reply":"2023-07-05T09:30:51.056194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndf_tile_meta = pd.read_csv('/kaggle/input/hubmap-hacking-the-human-vasculature/tile_meta.csv')\ndf_wsi_meta = pd.read_csv('/kaggle/input/hubmap-hacking-the-human-vasculature/wsi_meta.csv')\nprint(df_tile_meta.head())\nprint(df_wsi_meta.head())\n\n# Extract label and size columns    \nlabels = df_wsi_meta['sex'] \nsizes = df_wsi_meta['age']\n# Plot\nplt.pie(sizes, labels=labels, autopct='%1.1f%%',\n        shadow=True, startangle=140)\n# Draw circle at center\n#centre_circle = plt.Circle((0,0),0.70,fc='white') \n#fig = plt.gcf()\n#fig.gca().add_artist(centre_circle)\n# Show the chart\nplt.show() \n# Set x & y axis data      \nx = df_wsi_meta['age']\ny = df_wsi_meta['bmi']\n# Plot bars     \nplt.bar(x, y, color='r')\n# Add title and axis names\nplt.title(\"BMI by Source ID\") \nplt.xlabel(\"Source ID\")\nplt.ylabel(\"BMI\")\n# Show bar chart   \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.058579Z","iopub.execute_input":"2023-07-05T09:30:51.059116Z","iopub.status.idle":"2023-07-05T09:30:51.469285Z","shell.execute_reply.started":"2023-07-05T09:30:51.059082Z","shell.execute_reply":"2023-07-05T09:30:51.468381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nrandom.shuffle(active_train_Polygons)  \nsplit_idx = int(len(active_train_Polygons) * 0.8)  \ntrain_data = active_train_Polygons[:split_idx]\nval_data = active_train_Polygons[split_idx:]\nprint('train data length:',len(train_data))\nprint('val data length:',len(val_data))\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.470639Z","iopub.execute_input":"2023-07-05T09:30:51.471223Z","iopub.status.idle":"2023-07-05T09:30:51.776233Z","shell.execute_reply.started":"2023-07-05T09:30:51.471190Z","shell.execute_reply":"2023-07-05T09:30:51.775100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#for train_item in train_data:\n   # train_item.build_YOLOFormat_images_labels(train_dir)\n#for val_item in val_data:\n   # val_item.build_YOLOFormat_images_labels(val_dir)\n    ","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.778302Z","iopub.execute_input":"2023-07-05T09:30:51.778617Z","iopub.status.idle":"2023-07-05T09:30:51.785996Z","shell.execute_reply.started":"2023-07-05T09:30:51.778592Z","shell.execute_reply":"2023-07-05T09:30:51.785089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#%pip uninstall ultralytics --yes\n#%pip install ultralytics","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.787493Z","iopub.execute_input":"2023-07-05T09:30:51.787967Z","iopub.status.idle":"2023-07-05T09:30:51.795410Z","shell.execute_reply.started":"2023-07-05T09:30:51.787936Z","shell.execute_reply":"2023-07-05T09:30:51.794407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#from kaggle_secrets import UserSecretsClient\n#user_secrets = UserSecretsClient()\n#secret_value_0 = user_secrets.get_secret(\"wandb_Key\")\n#wandb.login(key=secret_value_0)\n#wandb.init(project=\"Kaggle_Humap\")","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.796794Z","iopub.execute_input":"2023-07-05T09:30:51.797279Z","iopub.status.idle":"2023-07-05T09:30:51.805498Z","shell.execute_reply.started":"2023-07-05T09:30:51.797248Z","shell.execute_reply":"2023-07-05T09:30:51.804541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.append(\"/kaggle/input/yolov8/ultralytics-main\")","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.806737Z","iopub.execute_input":"2023-07-05T09:30:51.807059Z","iopub.status.idle":"2023-07-05T09:30:51.815684Z","shell.execute_reply.started":"2023-07-05T09:30:51.807026Z","shell.execute_reply":"2023-07-05T09:30:51.814845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from ultralytics import YOLO\n\n#model = YOLO('yolov8n-seg.yaml')  # build a new model from YAML\n#model = YOLO('yolov8n-seg.pt')  # load a pretrained model (recommended for training)","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.818504Z","iopub.execute_input":"2023-07-05T09:30:51.818759Z","iopub.status.idle":"2023-07-05T09:30:51.826546Z","shell.execute_reply.started":"2023-07-05T09:30:51.818738Z","shell.execute_reply":"2023-07-05T09:30:51.825632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\n#odel.train(data='/kaggle/input/dataset/dataset.yaml', epochs=35, imgsz=512,batch=15)","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.829598Z","iopub.execute_input":"2023-07-05T09:30:51.829983Z","iopub.status.idle":"2023-07-05T09:30:51.836411Z","shell.execute_reply.started":"2023-07-05T09:30:51.829952Z","shell.execute_reply":"2023-07-05T09:30:51.835489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Export the model\n#model.export()\n#model = YOLO(\"/kaggle/input/yolov8best/best.onnx\")\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.837692Z","iopub.execute_input":"2023-07-05T09:30:51.838132Z","iopub.status.idle":"2023-07-05T09:30:51.844825Z","shell.execute_reply.started":"2023-07-05T09:30:51.838102Z","shell.execute_reply":"2023-07-05T09:30:51.843865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#from IPython.display import FileLink\n#FileLink(r'runs/segment/train/weights/best.torchscript')\n#FileLink(r'runs/segment/train/weights/best.pt')","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.846201Z","iopub.execute_input":"2023-07-05T09:30:51.846546Z","iopub.status.idle":"2023-07-05T09:30:51.856152Z","shell.execute_reply.started":"2023-07-05T09:30:51.846515Z","shell.execute_reply":"2023-07-05T09:30:51.855184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#!pip install pycocotools\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.857849Z","iopub.execute_input":"2023-07-05T09:30:51.858575Z","iopub.status.idle":"2023-07-05T09:30:51.866608Z","shell.execute_reply.started":"2023-07-05T09:30:51.858545Z","shell.execute_reply":"2023-07-05T09:30:51.865629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nHOME = os.getcwd()\n!mkdir /kaggle/working/packages\n!cp -r /kaggle/input/pycocotools/* /kaggle/working/packages\nos.chdir(\"/kaggle/working/packages/pycocotools-2.0.6/\")\n!python setup.py install\n!pip install . --no-index --find-links /kaggle/working/packages/\nos.chdir(\"/kaggle/working\")\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:30:51.869250Z","iopub.execute_input":"2023-07-05T09:30:51.869708Z","iopub.status.idle":"2023-07-05T09:31:30.922234Z","shell.execute_reply.started":"2023-07-05T09:30:51.869678Z","shell.execute_reply":"2023-07-05T09:31:30.920862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = YOLO('/kaggle/input/yolobest/best.pt')","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:31:30.924074Z","iopub.execute_input":"2023-07-05T09:31:30.924474Z","iopub.status.idle":"2023-07-05T09:31:30.995707Z","shell.execute_reply.started":"2023-07-05T09:31:30.924437Z","shell.execute_reply":"2023-07-05T09:31:30.994795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import base64\nimport numpy as np\nfrom pycocotools import _mask as coco_mask\nimport typing as t\nimport zlib\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:31:30.997052Z","iopub.execute_input":"2023-07-05T09:31:30.997411Z","iopub.status.idle":"2023-07-05T09:31:31.003865Z","shell.execute_reply.started":"2023-07-05T09:31:30.997378Z","shell.execute_reply":"2023-07-05T09:31:31.002867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def encode_binary_mask(mask: np.ndarray) -> t.Text:\n \"\"\"Converts a binary mask into OID challenge encoding ascii text.\"\"\"\n\n # check input mask --\n if mask.dtype != np.bool:\n   raise ValueError(\n       \"encode_binary_mask expects a binary mask, received dtype == %s\" %\n       mask.dtype)\n\n mask = np.squeeze(mask)\n if len(mask.shape) != 2:\n   raise ValueError(\n       \"encode_binary_mask expects a 2d mask, received shape == %s\" %\n       mask.shape)\n\n # convert input mask to expected COCO API input --\n mask_to_encode = mask.reshape(mask.shape[0], mask.shape[1], 1)\n mask_to_encode = mask_to_encode.astype(np.uint8)\n mask_to_encode = np.asfortranarray(mask_to_encode)\n\n # RLE encode mask --\n encoded_mask = coco_mask.encode(mask_to_encode)[0][\"counts\"]\n\n # compress and base64 encoding --\n binary_str = zlib.compress(encoded_mask, zlib.Z_BEST_COMPRESSION)\n base64_str = base64.b64encode(binary_str)\n return base64_str\n\n# 读取测试图像\nimage_path = '/kaggle/input/hubmap-hacking-the-human-vasculature/test/72e40acccadf.tif'\nimage_test = cv2.imread(image_path)\n\n# 模型推理\nresults = model.predict(image_test,imgsz=512,conf=0.2,iou=0.6,retina_masks=True)\n#results = model.predict(image_test,iou=0.6,imgsz=512, conf=0.6,retina_masks=True)\n\nprint('masks shape:',results[0].masks.shape)\n#print(results[0].masks.segments)\nprint('classes:',results[0].boxes.cls)\nprint('box data:',results[0].boxes.data[0][4])\n\n\n\n\nboxes = results[0].boxes\nencoded_masks = results[0].masks.data.cpu().numpy()\nconfidences = results[0].boxes.conf.cpu().numpy()\n\nprediction_string = ''\nprint('c :',confidences)\nfor idx, encoded_mask in enumerate(encoded_masks):\n    \n    \n    encoded_mask = encoded_mask.astype(np.bool)\n    encoded_mask_string = encode_binary_mask(encoded_mask).decode('utf-8')\n    prediction_string += '0 '+ str(confidences[idx]) +' '+ encoded_mask_string +' ' \n\n# 生成submission字符串\nimage_id = '72e40acccadf'\nimage_height, image_width = image_test.shape[:2]\nresults_csv = pd.DataFrame([], columns=[\"id\",\"height\",\"width\",\"prediction_string\"])\nresults_csv.set_index(\"id\")\n\nrow = dict()\nrow[\"id\"] = image_id\nrow[\"height\"] = image_height\nrow[\"width\"] = image_width\nrow[\"prediction_string\"] = prediction_string\n        \nnew_row = pd.DataFrame(row, index=[0])\nresults_csv = pd.concat([new_row, results_csv.loc[:]]).reset_index(drop=True)\n\nresults_csv.to_csv(\"submission.csv\", index=False)\n\n\n\n!cat submission.csv\n","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:31:31.009962Z","iopub.execute_input":"2023-07-05T09:31:31.010266Z","iopub.status.idle":"2023-07-05T09:31:32.196513Z","shell.execute_reply.started":"2023-07-05T09:31:31.010243Z","shell.execute_reply":"2023-07-05T09:31:32.195316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nres_plotted = results[0].plot()\n\n# 绘制图像\nplt.imshow(cv2.cvtColor(res_plotted, cv2.COLOR_BGR2RGB))\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:31:32.199194Z","iopub.execute_input":"2023-07-05T09:31:32.200027Z","iopub.status.idle":"2023-07-05T09:31:32.417681Z","shell.execute_reply.started":"2023-07-05T09:31:32.199987Z","shell.execute_reply":"2023-07-05T09:31:32.416774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#wandb.finish()","metadata":{"execution":{"iopub.status.busy":"2023-07-05T09:31:32.419251Z","iopub.execute_input":"2023-07-05T09:31:32.419867Z","iopub.status.idle":"2023-07-05T09:31:32.423642Z","shell.execute_reply.started":"2023-07-05T09:31:32.419836Z","shell.execute_reply":"2023-07-05T09:31:32.422804Z"},"trusted":true},"execution_count":null,"outputs":[]}]}