{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm.notebook import tqdm_notebook as tqdm\nimport shutil","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"ships = pd.read_csv(\"/kaggle/input/airbus-ship-detection/train_ship_segmentations_v2.csv\")\ntest_data = pd.read_csv(\"/kaggle/input/airbus-ship-detection/sample_submission_v2.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ships[\"Ship\"] = ships[\"EncodedPixels\"].map(lambda x:1 if isinstance(x,str) else 0)\nship_unique = ships[[\"ImageId\",\"Ship\"]].groupby(\"ImageId\").agg({\"Ship\":\"sum\"}).reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def rle2bbox(rle, shape):\n    \n    a = np.fromiter(rle.split(), dtype=np.uint)\n    a = a.reshape((-1, 2))\n    a[:,0] -= 1\n    \n    y0 = a[:,0] % shape[0]\n    y1 = y0 + a[:,1]\n    if np.any(y1 > shape[0]):\n        y0 = 0\n        y1 = shape[0]\n    else:\n        y0 = np.min(y0)\n        y1 = np.max(y1)\n    \n    x0 = a[:,0] // shape[0]\n    x1 = (a[:,0] + a[:,1]) // shape[0]\n    x0 = np.min(x0)\n    x1 = np.max(x1)\n    \n    if x1 > shape[1]:\n        raise ValueError(\"invalid RLE or image dimensions: x1=%d > shape[1]=%d\" % (\n            x1, shape[1]\n        ))\n\n    xc = (x0+x1)/(2*768)\n    yc = (y0+y1)/(2*768)\n    w = np.abs(x1-x0)/768\n    h = np.abs(y1-y0)/768\n    return [xc, yc, h, w]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Normalleştirilmiş kodlanmış piksellerden sınırlayıcı kutuları bulma\nships[\"Boundingbox\"] = ships[\"EncodedPixels\"].apply(lambda x:rle2bbox(x,(768,768)) if isinstance(x,str) else np.NaN)\nships.drop(\"EncodedPixels\", axis =1, inplace =True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ships[\"BoundingboxArea\"]=ships[\"Boundingbox\"].map(lambda x:x[2]*768*x[3]*768 if x==x else 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#%1'den az olan kutuları kaldırma\nships = ships[ships[\"BoundingboxArea\"]>np.percentile(ships[\"BoundingboxArea\"],1)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"balanced_df = ship_unique.groupby(\"Ship\").apply(lambda x:x.sample(1000) if len(x)>=1000 else x.sample(len(x)))\nbalanced_df.reset_index(drop=True,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Balanced_df'deki görüntüler için Sınırlayıcı kutular için veri çerçevesi oluşturma\nbalanced_bbox = ships.merge(balanced_df[[\"ImageId\"]], how =\"inner\", on = \"ImageId\")\nbalanced_bbox.head(20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Sınırlayıcı kutuları ve görüntüleri görselleştirme\npath =\"../input/airbus-ship-detection/train_v2/\"\nplt.figure(figsize =(20,20))\nfor i in range(15):\n    imageid = balanced_df[balanced_df.Ship ==i].iloc[0][0]\n    image = np.array(cv2.imread(path+imageid)[:,:,::-1])\n    if i>0:\n        bbox = balanced_bbox[balanced_bbox.ImageId==imageid][\"Boundingbox\"]\n        \n        for items in bbox:\n            Xmin  = int((items[0]-items[3]/2)*768)\n            Ymin  = int((items[1]-items[2]/2)*768)\n            Xmax  = int((items[0]+items[3]/2)*768)\n            Ymax  = int((items[1]+items[2]/2)*768)\n            cv2.rectangle(image,\n                          (Xmin,Ymin),\n                          (Xmax,Ymax),\n                          (255,0,0),\n                          thickness = 2)\n    plt.subplot(4,4,i+1)\n    plt.imshow(image)\n    plt.title(\"Bulunan gemi sayısı = {}\".format(i))\n","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}