{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":24800,"databundleVersionId":1831594,"sourceType":"competition"},{"sourceId":10071871,"sourceType":"datasetVersion","datasetId":6208005},{"sourceId":10115739,"sourceType":"datasetVersion","datasetId":6241250}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Cài đặt các thư viện cần thiết\n!pip install seaborn pydicom opencv-python-headless torch torchvision torch-xla pydicom","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thực hiện chức năng thống kê phân bố theo chiều rộng của các bức ảnh dicom ban đầu\nimport os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom collections import Counter\nfrom concurrent.futures import ThreadPoolExecutor\nimport torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file DICOM\ndicom_dir = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/'\n\n# Đường dẫn để lưu biểu đồ\noutput_path = '/kaggle/working/width.png'\n\n# Danh sách lưu chiều rộng của mỗi bức ảnh DICOM\nwidths = []\n\n# Hàm đọc chiều rộng từ một file DICOM\ndef read_dicom_width(dicom_file):\n    dicom_path = os.path.join(dicom_dir, dicom_file)\n    if (dicom_file.endswith('.dcm') or dicom_file.endswith('.dicom')) and os.path.isfile(dicom_path):\n        try:\n            dicom_data = pydicom.dcmread(dicom_path)\n            return dicom_data.Columns\n        except Exception as e:\n            print(f\"Error reading {dicom_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để đọc file DICOM song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(read_dicom_width, os.listdir(dicom_dir)))\n\n# Lọc ra các chiều rộng không phải là None\nwidths = [width for width in results if width is not None]\n\n# Kiểm tra nếu danh sách widths không rỗng\nif widths:\n    # Thiết lập độ rộng bin cho histogram là 100 pixel\n    bin_width = 100\n    width_bins = range(min(widths), max(widths) + bin_width, bin_width)\n\n    # Đếm số lượng mỗi giá trị của chiều rộng\n    width_counts = Counter(widths)\n    unique_widths = list(width_counts.keys())\n    counts = list(width_counts.values())\n\n    # Tạo figure cho 2 biểu đồ con\n    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 10))\n    # Biểu đồ con thứ 1: Phân bố chiều rộng sử dụng các đường thẳng đứng\n    ax1.vlines(unique_widths, ymin=0, ymax=counts, color='blue', alpha=0.6)\n    ax1.set_xlabel(\"Chiều rộng của ảnh (pixels)\")\n    ax1.set_ylabel(\"Số lượng ảnh\")\n    ax1.set_title(\"Biểu đồ phân bố tần suất theo chiều rộng của các bức ảnh DICOM\")\n    ax1.grid(True)\n\n    # Biểu đồ con thứ 2: Histogram chiều rộng với KDE\n    sns.histplot(widths, bins=width_bins, kde=True, color='blue', edgecolor='red', ax=ax2)\n    ax2.set_xlabel(\"Chiều rộng của ảnh (pixels)\")\n    ax2.set_ylabel(\"Số lượng ảnh\")\n    ax2.set_title(\"Biểu đồ phân bố tần suất theo chiều rộng của các bức ảnh DICOM - KDE\")\n    ax2.grid(axis='y', linestyle='--', alpha=0.7)\n\n    # Thêm chú thích về độ rộng bin\n    bin_label = f\"Bin width: {bin_width} pixels\"\n    ax2.text(0.98, 0.95, bin_label, transform=ax2.transAxes, fontsize=10,\n         verticalalignment='top', horizontalalignment='right', color='black')\n\n    # Điều chỉnh khoảng cách giữa các biểu đồ con\n    plt.tight_layout(pad=2.0)\n\n    # Lưu biểu đồ thành file\n    plt.savefig(output_path)\n    plt.show()\nelse:\n    print(\"Không tìm thấy file DICOM nào trong thư mục.\")\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thực hiện chức năng thống kê phân bố theo chiều cao của các bức ảnh dicom ban đầu\nimport os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom collections import Counter\nfrom concurrent.futures import ThreadPoolExecutor\nimport torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file DICOM\ndicom_dir = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/'\n\n# Đường dẫn để lưu biểu đồ\noutput_path = '/kaggle/working/height.png'\n\n# Danh sách lưu chiều cao của mỗi bức ảnh DICOM\nheights = []\n\n# Hàm đọc chiều cao từ một file DICOM\ndef read_dicom_height(dicom_file):\n    dicom_path = os.path.join(dicom_dir, dicom_file)\n    if (dicom_file.endswith('.dcm') or dicom_file.endswith('.dicom')) and os.path.isfile(dicom_path):\n        try:\n            dicom_data = pydicom.dcmread(dicom_path)\n            return dicom_data.Rows  # Đọc chiều cao từ trường Rows\n        except Exception as e:\n            print(f\"Error reading {dicom_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để đọc file DICOM song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(read_dicom_height, os.listdir(dicom_dir)))\n\n# Lọc ra các chiều cao không phải là None\nheights = [height for height in results if height is not None]\n\n# Kiểm tra nếu danh sách heights không rỗng\nif heights:\n    # Thiết lập độ rộng bin cho histogram là 100 pixel\n    bin_height = 100\n    height_bins = range(min(heights), max(heights) + bin_height, bin_height)\n\n    # Đếm số lượng mỗi giá trị của chiều cao\n    height_counts = Counter(heights)\n    unique_heights = list(height_counts.keys())\n    counts = list(height_counts.values())\n\n    # Tạo figure cho 2 biểu đồ con\n    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 10))\n    # Biểu đồ con thứ 1: Phân bố chiều cao sử dụng các đường thẳng đứng\n    ax1.vlines(unique_heights, ymin=0, ymax=counts, color='blue', alpha=0.6)\n    ax1.set_xlabel(\"Chiều cao của ảnh (pixels)\")\n    ax1.set_ylabel(\"Số lượng ảnh\")\n    ax1.set_title(\"Biểu đồ phân bố tần suất theo chiều cao của các bức ảnh DICOM\")\n    ax1.grid(True)\n\n    # Biểu đồ con thứ 2: Histogram chiều cao với KDE\n    sns.histplot(heights, bins=height_bins, kde=True, color='blue', edgecolor='red', ax=ax2)\n    ax2.set_xlabel(\"Chiều cao của ảnh (pixels)\")\n    ax2.set_ylabel(\"Số lượng ảnh\")\n    ax2.set_title(\"Biểu đồ phân bố tần suất theo chiều cao của các bức ảnh DICOM - KDE\")\n    ax2.grid(axis='y', linestyle='--', alpha=0.7)\n    \n    # Thêm chú thích về độ rộng bin\n    bin_label = f\"Bin width: {bin_width} pixels\"\n    ax2.text(0.98, 0.95, bin_label, transform=ax2.transAxes, fontsize=10,\n         verticalalignment='top', horizontalalignment='right', color='black')\n\n    # Điều chỉnh khoảng cách giữa các biểu đồ con\n    plt.tight_layout(pad=2.0)\n\n    # Lưu biểu đồ thành file\n    plt.savefig(output_path)\n    plt.show()\nelse:\n    print(\"Không tìm thấy file DICOM nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thực hiện chức năng thống kê phân bố theo chiều cao và chiều rộng của các bức ảnh dicom ban đầu\nimport os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom collections import Counter\nfrom concurrent.futures import ThreadPoolExecutor\nimport torch\nimport numpy as np  # Nhập khẩu thư viện NumPy\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file DICOM\ndicom_dir = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/'\n\n# Đường dẫn để lưu biểu đồ\noutput_path = '/kaggle/working/width_height_distribution.png'\n\n# Danh sách lưu chiều rộng và chiều cao của mỗi bức ảnh DICOM\nwidths = []\nheights = []\n\n# Hàm đọc chiều rộng và chiều cao từ một file DICOM\ndef read_dicom_dimensions(dicom_file):\n    dicom_path = os.path.join(dicom_dir, dicom_file)\n    if (dicom_file.endswith('.dcm') or dicom_file.endswith('.dicom')) and os.path.isfile(dicom_path):\n        try:\n            dicom_data = pydicom.dcmread(dicom_path)\n            return dicom_data.Columns, dicom_data.Rows  # Đọc chiều rộng và chiều cao\n        except Exception as e:\n            print(f\"Error reading {dicom_file}: {e}\")\n            return None, None\n    return None, None\n\n# Sử dụng ThreadPoolExecutor để đọc file DICOM song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(read_dicom_dimensions, os.listdir(dicom_dir)))\n\n# Lọc ra các chiều rộng và chiều cao không phải là None\nfor width, height in results:\n    if width is not None and height is not None:\n        widths.append(width)\n        heights.append(height)\n\n# Kiểm tra nếu danh sách widths và heights không rỗng\nif widths and heights:\n    # Tạo figure cho 2 biểu đồ con\n    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 10))\n\n    # Hình 1: Phân bố theo cả chiều rộng và chiều cao\n    ax1.scatter(widths, heights, alpha=0.6, color='blue', edgecolor='black')\n    ax1.set_xlabel(\"Chiều rộng của ảnh (pixels)\")\n    ax1.set_ylabel(\"Chiều cao của ảnh (pixels)\")\n    ax1.set_title(\"Biểu đồ phân tán theo chiều rộng và chiều cao của các bức ảnh DICOM\")\n    ax1.grid(True)\n\n    # Hình 2: Biểu đồ nhiệt độ (Heatmap) với thang màu Purples\n    heatmap, xedges, yedges = np.histogram2d(widths, heights, bins=30)\n    img = ax2.imshow(heatmap.T, origin='lower', cmap='Reds', interpolation='nearest', aspect='auto',\n                     extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])\n    ax2.set_xlabel(\"Chiều rộng của ảnh (pixels)\")\n    ax2.set_ylabel(\"Chiều cao của ảnh (pixels)\")\n    ax2.set_title(\"Biểu đồ phân tán theo chiều rộng và chiều cao của các bức ảnh DICOM\")\n    ax2.grid(False)\n\n    # Thêm thanh màu cho biểu đồ nhiệt độ\n    cbar = plt.colorbar(img, ax=ax2)\n    cbar.set_label(\"Số lượng ảnh\")\n\n    ax2.set_facecolor('green')  # Đặt màu nền cho ax2 là cyan\n\n    # Điều chỉnh khoảng cách giữa các biểu đồ con\n    plt.tight_layout(pad=2.0)\n\n    # Lưu biểu đồ thành file\n    plt.savefig(output_path)\n    plt.show()\nelse:\n    print(\"Không tìm thấy file DICOM nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thực hiện chức năng thống kê phân bố số mẫu theo các phân lớp\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Đường dẫn đến tệp train.csv\nfile_path = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train.csv'\n\n# Đọc tệp CSV\ntrain_data = pd.read_csv(file_path)\n\n# Tính toán số lượng hình ảnh theo class_id\nclass_counts = train_data['class_id'].value_counts().reset_index()\nclass_counts.columns = ['class_id', 'count']\n\n# Thêm tên lớp tương ứng\nclass_counts = class_counts.merge(train_data[['class_id', 'class_name']].drop_duplicates(), on='class_id')\n\n# Vẽ biểu đồ\nf, ax = plt.subplots(1, 1, figsize=(12, 10))\ntotal = float(len(train_data))\n\n# Vẽ biểu đồ countplot\nsns.countplot(data=train_data, x='class_id', order=class_counts['class_id'], palette='tab20', ax=ax)\n\n# Thêm nhãn phần trăm lên từng cột\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x() + p.get_width() / 2.,\n            height + 3,\n            '{:1.2f}%'.format(100 * height / total),\n            ha=\"center\")\n\n# Thêm tiêu đề và nhãn\nax.set_title('Number of Images by Class ID', fontsize=16)\nax.set_xlabel('Class ID', fontsize=14)\nax.set_ylabel('Count', fontsize=14)\n\n# Thêm legend cho class_name và class_id\nhandles = [plt.Line2D([0], [0], marker='o', color='w', label=f'Class ID: {class_id} - {class_name}',\n                       markerfacecolor=sns.color_palette(\"tab20\")[i],\n                       markersize=10) for i, (class_id, class_name) in enumerate(zip(class_counts['class_id'], class_counts['class_name']))]\nax.legend(title='Class ID and Name', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình vẽ đồ thị box plot cho chiều rộng, chiều cao\nimport os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom collections import Counter\nfrom concurrent.futures import ThreadPoolExecutor\nimport torch\nimport numpy as np  # Nhập khẩu thư viện NumPy\n\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file DICOM\ndicom_dir = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/'\n\n# Đường dẫn để lưu biểu đồ\noutput_path = '/kaggle/working/width_height_boxplot.png'\n\n# Danh sách lưu chiều rộng và chiều cao của mỗi bức ảnh DICOM\nwidths = []\nheights = []\n\n# Hàm đọc chiều rộng và chiều cao từ một file DICOM\ndef read_dicom_dimensions(dicom_file):\n    dicom_path = os.path.join(dicom_dir, dicom_file)\n    if (dicom_file.endswith('.dcm') or dicom_file.endswith('.dicom')) and os.path.isfile(dicom_path):\n        try:\n            dicom_data = pydicom.dcmread(dicom_path)\n            return dicom_data.Columns, dicom_data.Rows  # Đọc chiều rộng và chiều cao\n        except Exception as e:\n            print(f\"Error reading {dicom_file}: {e}\")\n            return None, None\n    return None, None\n\n# Sử dụng ThreadPoolExecutor để đọc file DICOM song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(read_dicom_dimensions, os.listdir(dicom_dir)))\n\n# Lọc ra các chiều rộng và chiều cao không phải là None\nfor width, height in results:\n    if width is not None and height is not None:\n        widths.append(width)\n        heights.append(height)\n\n# Kiểm tra nếu danh sách widths và heights không rỗng\nif widths and heights:\n    # Tạo figure cho box plot\n    fig, ax = plt.subplots(figsize=(10, 6))\n\n    # Tạo box plot cho chiều rộng và chiều cao\n    sns.boxplot(data=[widths, heights], ax=ax, palette='Set2')\n    ax.set_xticklabels(['Chiều rộng (pixels)', 'Chiều cao (pixels)'])\n    ax.set_ylabel(\"Giá trị (pixels)\")\n    ax.set_title(\"Box Plot cho chiều rộng và chiều cao của các bức ảnh DICOM\")\n\n    # Lưu biểu đồ thành file\n    plt.tight_layout(pad=2.0)\n    plt.savefig(output_path)\n    plt.show()\nelse:\n    print(\"Không tìm thấy file DICOM nào trong thư mục.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T02:24:00.035662Z","iopub.execute_input":"2024-12-13T02:24:00.036001Z","iopub.status.idle":"2024-12-13T02:27:29.220383Z","shell.execute_reply.started":"2024-12-13T02:24:00.035964Z","shell.execute_reply":"2024-12-13T02:27:29.219515Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thực hiện chức năng vẽ biểu đồ 3D phân bố theo chiều cao và chiều rộng của các bức ảnh dicom ban đầu\nimport os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom concurrent.futures import ThreadPoolExecutor\nimport torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file DICOM\ndicom_dir = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/'\n\n# Đường dẫn để lưu biểu đồ\noutput_path_3d = '/kaggle/working/width_height_3d.png'\n\n# Danh sách lưu chiều rộng và chiều cao của mỗi bức ảnh DICOM\nwidths = []\nheights = []\n\n# Hàm đọc chiều rộng và chiều cao từ một file DICOM\ndef read_dicom_dimensions(dicom_file):\n    dicom_path = os.path.join(dicom_dir, dicom_file)\n    if (dicom_file.endswith('.dcm') or dicom_file.endswith('.dicom')) and os.path.isfile(dicom_path):\n        try:\n            dicom_data = pydicom.dcmread(dicom_path)\n            return dicom_data.Columns, dicom_data.Rows  # Đọc chiều rộng và chiều cao\n        except Exception as e:\n            print(f\"Error reading {dicom_file}: {e}\")\n            return None, None\n    return None, None\n\n# Sử dụng ThreadPoolExecutor để đọc file DICOM song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(read_dicom_dimensions, os.listdir(dicom_dir)))\n\n# Lọc ra các chiều rộng và chiều cao không phải là None\nfor width, height in results:\n    if width is not None and height is not None:\n        widths.append(width)\n        heights.append(height)\n\n# Kiểm tra nếu danh sách widths và heights không rỗng\nif widths and heights:\n    # Tạo histogram 2D để tính số lượng ảnh cho mỗi cặp chiều rộng và chiều cao\n    heatmap, xedges, yedges = np.histogram2d(widths, heights, bins=30)\n\n    # Tạo figure cho biểu đồ 3D\n    fig = plt.figure(figsize=(10, 8))\n    ax = fig.add_subplot(111, projection='3d')\n\n    # Tạo các giá trị X, Y và Z cho biểu đồ 3D\n    xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1], indexing=\"ij\")\n    xpos = xpos.ravel()\n    ypos = ypos.ravel()\n    zpos = np.zeros_like(xpos)  # Z bắt đầu từ 0\n\n    # Chiều cao của mỗi cột trong biểu đồ là số lượng ảnh\n    dx = dy = 0.5 * np.ones_like(zpos)  # Độ rộng và chiều cao của các cột\n    dz = heatmap.ravel()  # Số lượng ảnh\n\n    # Vẽ biểu đồ 3D\n    ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average', alpha=0.6, color='red', edgecolor='blue')\n\n    ax.set_xlabel(\"Chiều rộng của ảnh (pixels)\")\n    ax.set_ylabel(\"Chiều cao của ảnh (pixels)\")\n    ax.set_zlabel(\"Số lượng ảnh\")\n    ax.set_title(\"Biểu đồ 3D giữa chiều rộng, chiều cao và số lượng ảnh DICOM\")\n\n    # Lưu biểu đồ thành file\n    plt.tight_layout(pad=2.0)\n    plt.savefig(output_path_3d)\n    plt.show()\nelse:\n    print(\"Không tìm thấy file DICOM nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình vẽ biểu đồ heatmap phân bố theo chiều cao và chiều rộng của các bức ảnh dicom ban đầu\nimport os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom concurrent.futures import ThreadPoolExecutor\nimport torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file DICOM\ndicom_dir = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/'\n\n# Đường dẫn để lưu biểu đồ\noutput_path_heatmap = '/kaggle/working/width_height_heatmap.png'\n\n# Danh sách lưu chiều rộng và chiều cao của mỗi bức ảnh DICOM\nwidths = []\nheights = []\n\n# Hàm đọc chiều rộng và chiều cao từ một file DICOM\ndef read_dicom_dimensions(dicom_file):\n    dicom_path = os.path.join(dicom_dir, dicom_file)\n    if (dicom_file.endswith('.dcm') or dicom_file.endswith('.dicom')) and os.path.isfile(dicom_path):\n        try:\n            dicom_data = pydicom.dcmread(dicom_path)\n            return dicom_data.Columns, dicom_data.Rows  # Đọc chiều rộng và chiều cao\n        except Exception as e:\n            print(f\"Error reading {dicom_file}: {e}\")\n            return None, None\n    return None, None\n\n# Sử dụng ThreadPoolExecutor để đọc file DICOM song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(read_dicom_dimensions, os.listdir(dicom_dir)))\n\n# Lọc ra các chiều rộng và chiều cao không phải là None\nfor width, height in results:\n    if width is not None and height is not None:\n        widths.append(width)\n        heights.append(height)\n\n# Kiểm tra nếu danh sách widths và heights không rỗng\nif widths and heights:\n    # Tạo histogram 2D để tính số lượng ảnh cho mỗi cặp chiều rộng và chiều cao\n    heatmap, xedges, yedges = np.histogram2d(widths, heights, bins=30)\n\n    # Tạo biểu đồ nhiệt\n    plt.figure(figsize=(10, 6))\n    plt.imshow(heatmap.T, origin='lower', cmap='Purples', interpolation='nearest', aspect='auto',\n               extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])\n    plt.colorbar(label='Số lượng ảnh')\n    plt.xlabel(\"Chiều rộng của ảnh (pixels)\")\n    plt.ylabel(\"Chiều cao của ảnh (pixels)\")\n    plt.title(\"Biểu đồ heatmap giữa chiều rộng và chiều cao của các bức ảnh DICOM\")\n\n    # Lưu biểu đồ thành file\n    plt.tight_layout(pad=2.0)\n    plt.savefig(output_path_heatmap)\n    plt.show()\nelse:\n    print(\"Không tìm thấy file DICOM nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện phân bố độ lệch chuẩn pixel intensity của các bức ảnh gốc ban đầu\n!pip install torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo/'\n\n# Danh sách để lưu độ lệch chuẩn\nstd_devs = []\n\n# Hàm tính độ lệch chuẩn cho một file PNG\ndef calculate_std_dev(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n            \n            # Tính độ lệch chuẩn của dữ liệu pixel\n            return np.std(image_data)\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để tính toán độ lệch chuẩn song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_std_dev, os.listdir(png_dir)))\n\n# Lọc ra các độ lệch chuẩn không phải là None\nstd_devs = [std for std in results if std is not None]\n\n# Kiểm tra nếu danh sách std_devs không rỗng\nif std_devs:\n    # Tính khoảng giá trị của độ lệch chuẩn\n    std_range = max(std_devs) - min(std_devs)\n    \n    # Thiết lập độ rộng bin (đảm bảo là số nguyên)\n    num_bins = 30\n    bin_width = int(np.ceil(std_range / num_bins))  # Làm tròn lên thành số nguyên\n    \n    # Tạo các bin dựa trên bin_width\n    bins = range(int(min(std_devs)), int(max(std_devs)) + bin_width, bin_width)\n    \n    # Vẽ biểu đồ phân bố độ lệch chuẩn\n    plt.figure(figsize=(10, 6))\n    plt.hist(std_devs, bins=bins, color='lightblue', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Độ lệch chuẩn pixel intensity\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố độ lệch chuẩn pixel intensity của các bức ảnh PNG chưa qua xử lý\")\n    plt.grid()\n\n    # Thêm chú thích về độ rộng bin\n    bin_label = f\"Bin width: {bin_width}\"\n    plt.text(0.95, 0.95, bin_label, transform=plt.gca().transAxes,\n             fontsize=10, verticalalignment='top', horizontalalignment='right', color='black')\n\n    # Hiển thị biểu đồ\n    plt.tight_layout()\n    plt.show()\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện phân bố độ lệch chuẩn pixel intensity của các bức ảnh đã xử lý cân bằng\n!pip install torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo_clahe/'\n\n# Danh sách để lưu độ lệch chuẩn\nstd_devs = []\n\n# Hàm tính độ lệch chuẩn cho một file PNG\ndef calculate_std_dev(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n            \n            # Tính độ lệch chuẩn của dữ liệu pixel\n            return np.std(image_data)\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để tính toán độ lệch chuẩn song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_std_dev, os.listdir(png_dir)))\n\n# Lọc ra các độ lệch chuẩn không phải là None\nstd_devs = [std for std in results if std is not None]\n\n# Kiểm tra nếu danh sách std_devs không rỗng\nif std_devs:\n    # Tính khoảng giá trị của độ lệch chuẩn\n    std_range = max(std_devs) - min(std_devs)\n    \n    # Thiết lập độ rộng bin (làm tròn lên thành số nguyên)\n    num_bins = 30\n    bin_width = int(np.ceil(std_range / num_bins))  # Đảm bảo bin_width là số nguyên\n\n    # Tạo các bin dựa trên bin_width\n    bins = range(int(min(std_devs)), int(max(std_devs)) + bin_width, bin_width)\n    \n    # Vẽ biểu đồ phân bố độ lệch chuẩn\n    plt.figure(figsize=(10, 6))\n    plt.hist(std_devs, bins=bins, color='skyblue', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Độ lệch chuẩn pixel intensity\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố độ lệch chuẩn pixel intensity của các bức ảnh PNG đã xử lý cân bằng\")\n    plt.grid()\n    \n    # Thêm chú thích về độ rộng bin\n    bin_label = f\"Bin width: {bin_width}\"\n    plt.text(0.95, 0.95, bin_label, transform=plt.gca().transAxes,\n             fontsize=10, verticalalignment='top', horizontalalignment='right', color='black')\n    \n    # Hiển thị biểu đồ\n    plt.tight_layout()\n    plt.show()\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T02:31:48.714144Z","iopub.execute_input":"2024-12-13T02:31:48.714661Z","iopub.status.idle":"2024-12-13T02:33:46.073772Z","shell.execute_reply.started":"2024-12-13T02:31:48.714629Z","shell.execute_reply":"2024-12-13T02:33:46.072798Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện box plot độ lệch chuẩn pixel intensity của các bức ảnh gốc ban đầu\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch  # Nhập khẩu thư viện torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('======= Sử dụng GPU =======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('======= Sử dụng TPU =======')\nelse:\n    print('======= Sử dụng CPU =======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo/'\n\n# Danh sách để lưu độ lệch chuẩn\nstd_devs = []\n\n# Hàm tính độ lệch chuẩn cho một file PNG\ndef calculate_std_dev(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.lower().endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n            \n            # Tính độ lệch chuẩn của dữ liệu pixel\n            return np.std(image_data)\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để tính toán độ lệch chuẩn song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_std_dev, os.listdir(png_dir)))\n\n# Lọc ra các độ lệch chuẩn không phải là None\nstd_devs = [std for std in results if std is not None]\n\n# Kiểm tra nếu danh sách std_devs không rỗng\nif std_devs:\n    # Tính các giá trị Q1, Q2 (Median), Q3 và làm tròn chúng thành số nguyên\n    Q1 = int(np.round(np.percentile(std_devs, 25)))\n    median_value = np.median(std_devs)  # Median có thể giữ nguyên giá trị thập phân\n    Q3 = int(np.round(np.percentile(std_devs, 75)))\n    \n    # Vẽ Box Plot\n    plt.figure(figsize=(12, 7))\n    box = plt.boxplot(std_devs, vert=False, patch_artist=True,\n                      boxprops=dict(facecolor='lightblue', color='black'),\n                      medianprops=dict(color='red', linewidth=2),\n                      whiskerprops=dict(color='black'),\n                      capprops=dict(color='black'),\n                      flierprops=dict(marker='o', markerfacecolor='gray', markersize=5, linestyle='none'))\n    \n    # Vẽ các đường thẳng cho Q1, Q2, Q3 với Q1 và Q3 là số nguyên\n    plt.axvline(Q1, color='blue', linestyle='--', label=f'Q1 = {Q1}')\n    plt.axvline(median_value, color='red', linestyle='--', label=f'Median = {median_value:.2f}')\n    plt.axvline(Q3, color='green', linestyle='--', label=f'Q3 = {Q3}')\n    \n    # Thêm chú thích\n    plt.legend(loc='upper right', fontsize=12)\n    \n    # Cải thiện các giá trị trên trục hoành\n    plt.xlabel(\"Độ lệch chuẩn pixel intensity\", fontsize=12)\n    plt.title(\"Box Plot độ lệch chuẩn pixel intensity của các bức ảnh PNG chưa qua xử lý\", fontsize=14)\n    \n    # Tăng mật độ tick trên trục hoành\n    plt.xticks(ticks=np.round(np.linspace(min(std_devs), max(std_devs), 10), 2))  \n    plt.grid(alpha=0.5)\n    \n    # Thêm annotation cho Q1, Q2, Q3 với Q1 và Q3 là số nguyên\n    plt.text(Q1, 1.05, f'Q1: {Q1}', verticalalignment='bottom', horizontalalignment='right', color='blue', fontsize=10)\n    plt.text(median_value, 1.05, f'Median: {median_value:.2f}', verticalalignment='bottom', horizontalalignment='center', color='red', fontsize=10)\n    plt.text(Q3, 1.05, f'Q3: {Q3}', verticalalignment='bottom', horizontalalignment='left', color='green', fontsize=10)\n    \n    # Hiển thị biểu đồ\n    plt.tight_layout()\n    plt.show()\n\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T02:35:08.624656Z","iopub.execute_input":"2024-12-13T02:35:08.625058Z","iopub.status.idle":"2024-12-13T02:36:57.199214Z","shell.execute_reply.started":"2024-12-13T02:35:08.62502Z","shell.execute_reply":"2024-12-13T02:36:57.198382Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện box plot độ lệch chuẩn pixel intensity của các bức ảnh đã qua xử lý\n!pip install torch\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch  # Nhập khẩu thư viện torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('======= Sử dụng GPU =======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('======= Sử dụng TPU =======')\nelse:\n    print('======= Sử dụng CPU =======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo_clahe/'\n\n# Danh sách để lưu độ lệch chuẩn\nstd_devs = []\n\n# Hàm tính độ lệch chuẩn cho một file PNG\ndef calculate_std_dev(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.lower().endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n            \n            # Tính độ lệch chuẩn của dữ liệu pixel\n            return np.std(image_data)\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để tính toán độ lệch chuẩn song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_std_dev, os.listdir(png_dir)))\n\n# Lọc ra các độ lệch chuẩn không phải là None\nstd_devs = [std for std in results if std is not None]\n\n# Kiểm tra nếu danh sách std_devs không rỗng\nif std_devs:\n    # Tính các giá trị Q1, Q2 (Median), Q3 và làm tròn chúng thành số nguyên\n    Q1 = int(round(np.percentile(std_devs, 25)))\n    median_value = np.median(std_devs)\n    Q3 = int(round(np.percentile(std_devs, 75)))\n    \n    # Vẽ Box Plot\n    plt.figure(figsize=(12, 7))\n    box = plt.boxplot(std_devs, vert=False, patch_artist=True,\n                      boxprops=dict(facecolor='lightblue', color='black'),\n                      medianprops=dict(color='red', linewidth=2),\n                      whiskerprops=dict(color='black'),\n                      capprops=dict(color='black'),\n                      flierprops=dict(marker='o', markerfacecolor='gray', markersize=5, linestyle='none'))\n    \n    # Vẽ các đường thẳng cho Q1, Q2, Q3\n    plt.axvline(Q1, color='blue', linestyle='--', label=f'Q1 = {Q1}')\n    plt.axvline(median_value, color='red', linestyle='--', label=f'Median = {median_value:.2f}')\n    plt.axvline(Q3, color='green', linestyle='--', label=f'Q3 = {Q3}')\n    \n    # Thêm chú thích\n    plt.legend(loc='upper right', fontsize=12)\n    \n    # Cải thiện các giá trị trên trục hoành\n    plt.xlabel(\"Độ lệch chuẩn pixel intensity\", fontsize=12)\n    plt.title(\"Box Plot độ lệch chuẩn pixel intensity của các bức ảnh PNG đã qua xử lý cân bằng\", fontsize=14)\n    \n    # Tăng mật độ tick trên trục hoành\n    plt.xticks(ticks=np.round(np.linspace(min(std_devs), max(std_devs), 10), 2))  \n    plt.grid(alpha=0.5)\n    \n    # Thêm annotation cho Q1, Q2, Q3\n    plt.text(Q1, 1.05, f'Q1: {Q1}', verticalalignment='bottom', horizontalalignment='right', color='blue', fontsize=10)\n    plt.text(median_value, 1.05, f'Median: {median_value:.2f}', verticalalignment='bottom', horizontalalignment='center', color='red', fontsize=10)\n    plt.text(Q3, 1.05, f'Q3: {Q3}', verticalalignment='bottom', horizontalalignment='left', color='green', fontsize=10)\n    \n    # Hiển thị biểu đồ\n    plt.tight_layout()\n    plt.show()\n\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện biểu đố phân bố entropy của các bức ảnh gốc ban đầu\n!pip install torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch  # Nhập khẩu thư viện torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo/'\n\n# Danh sách để lưu entropy\nentropies = []\n\n# Hàm tính entropy cho một file PNG\ndef calculate_entropy(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n\n            # Tính histogram\n            hist, _ = np.histogram(image_data.flatten(), bins=256, range=[0, 256])\n            hist = hist / hist.sum()  # Chuẩn hóa histogram để thành xác suất\n            \n            # Tính entropy\n            return -np.sum(hist * np.log2(hist + 1e-10))  # Thêm epsilon để tránh log(0)\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để tính toán entropy song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_entropy, os.listdir(png_dir)))\n\n# Lọc ra các giá trị entropy không phải là None\nentropies = [entropy for entropy in results if entropy is not None]\n\n# Kiểm tra nếu danh sách entropies không rỗng\nif entropies:\n    # Vẽ biểu đồ phân bố entropy\n    plt.figure(figsize=(10, 6))\n    plt.hist(entropies, bins=30, color='skyblue', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Entropy\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố entropy của các bức ảnh PNG chưa qua xử lý\")\n    plt.grid()\n    \n    # Hiển thị biểu đồ histogram\n    plt.tight_layout()\n    plt.show()\n    \n    # Vẽ box plot cho entropy\n    plt.figure(figsize=(10, 6))\n    plt.boxplot(entropies, vert=False, patch_artist=True, boxprops=dict(facecolor='skyblue'))\n    plt.xlabel(\"Entropy\")\n    plt.title(\"Box Plot cho entropy của các bức ảnh PNG chưa qua xử lý\")\n    plt.grid()\n\n    # Hiển thị box plot\n    plt.tight_layout()\n    plt.show()\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện box plot độ lệch chuẩn pixel intensity của các bức ảnh đã qua xử lý\n!pip install torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch  # Nhập khẩu thư viện torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo_clahe/'\n\n# Danh sách để lưu entropy\nentropies = []\n\n# Hàm tính entropy cho một file PNG\ndef calculate_entropy(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n\n            # Tính histogram\n            hist, _ = np.histogram(image_data.flatten(), bins=256, range=[0, 256])\n            hist = hist / hist.sum()  # Chuẩn hóa histogram để thành xác suất\n            \n            # Tính entropy\n            return -np.sum(hist * np.log2(hist + 1e-10))  # Thêm epsilon để tránh log(0)\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để tính toán entropy song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_entropy, os.listdir(png_dir)))\n\n# Lọc ra các giá trị entropy không phải là None\nentropies = [entropy for entropy in results if entropy is not None]\n\n# Kiểm tra nếu danh sách entropies không rỗng\nif entropies:\n    # Vẽ biểu đồ phân bố entropy\n    plt.figure(figsize=(10, 6))\n    plt.hist(entropies, bins=30, color='lightgreen', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Entropy\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố entropy của các bức ảnh PNG đã qua xử lý cân bằng\")\n    plt.grid()\n    \n    # Hiển thị biểu đồ histogram\n    plt.tight_layout()\n    plt.show()\n    \n    # Vẽ box plot cho entropy\n    plt.figure(figsize=(10, 6))\n    plt.boxplot(entropies, vert=False, patch_artist=True, boxprops=dict(facecolor='lightgreen'))\n    plt.xlabel(\"Entropy\")\n    plt.title(\"Box Plot cho entropy của các bức ảnh PNG đã qua xử lý cân bằng\")\n    plt.grid()\n\n    # Hiển thị box plot\n    plt.tight_layout()\n    plt.show()\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện biểu đồ phân bố mức ảnh đen, trắng của các bức ảnh gốc ban đầu\n!pip install torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch  # Nhập khẩu thư viện torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo/'\n\n# Danh sách để lưu tỷ lệ pixel đen và trắng\nblack_pixel_ratios = []\nwhite_pixel_ratios = []\n\n# Hàm tính tỷ lệ pixel đen và trắng cho một file PNG\ndef calculate_pixel_ratios(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n            \n            # Tính số lượng pixel đen và trắng\n            total_pixels = image_data.size\n            black_pixels = np.sum(image_data == 0)  # Số pixel có giá trị 0 (đen)\n            white_pixels = np.sum(image_data == 255)  # Số pixel có giá trị 255 (trắng)\n            \n            # Tính tỷ lệ\n            black_pixel_ratio = black_pixels / total_pixels\n            white_pixel_ratio = white_pixels / total_pixels\n            \n            return black_pixel_ratio, white_pixel_ratio\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None, None\n    return None, None\n\n# Sử dụng ThreadPoolExecutor để tính toán tỷ lệ pixel song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_pixel_ratios, os.listdir(png_dir)))\n\n# Lọc ra các tỷ lệ không phải là None\nfor result in results:\n    if result is not None:\n        black_pixel_ratios.append(result[0])\n        white_pixel_ratios.append(result[1])\n\n# Kiểm tra nếu danh sách không rỗng\nif black_pixel_ratios and white_pixel_ratios:\n    # Vẽ biểu đồ phân bố tỷ lệ pixel tối đen\n    plt.figure(figsize=(10, 6))\n    plt.hist(black_pixel_ratios, bins=30, color='skyblue', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Tỷ lệ pixel màu đen\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố tỷ lệ pixel màu đen của các bức ảnh PNG chưa qua xử lý\")\n    plt.grid()\n    \n    # Hiển thị biểu đồ histogram\n    plt.tight_layout()\n    plt.show()\n\n    # Vẽ biểu đồ phân bố tỷ lệ pixel tối trắng\n    plt.figure(figsize=(10, 6))\n    plt.hist(white_pixel_ratios, bins=30, color='skyblue', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Tỷ lệ pixel màu trắng\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố tỷ lệ pixel màu trắng của các bức ảnh PNG chưa qua xử lý\")\n    plt.grid()\n    \n    # Hiển thị biểu đồ histogram\n    plt.tight_layout()\n    plt.show()\n\n    # Vẽ box plot cho tỷ lệ pixel tối đen\n    plt.figure(figsize=(10, 6))\n    plt.boxplot(black_pixel_ratios, vert=False, patch_artist=True, boxprops=dict(facecolor='skyblue'))\n    plt.xlabel(\"Tỷ lệ pixel màu đen\")\n    plt.title(\"Box Plot cho tỷ lệ pixel màu đen của các bức ảnh PNG chưa qua xử lý\")\n    plt.grid()\n\n    # Hiển thị box plot\n    plt.tight_layout()\n    plt.show()\n\n    # Vẽ box plot cho tỷ lệ pixel tối trắng\n    plt.figure(figsize=(10, 6))\n    plt.boxplot(white_pixel_ratios, vert=False, patch_artist=True, boxprops=dict(facecolor='skyblue'))\n    plt.xlabel(\"Tỷ lệ pixel màu trắng\")\n    plt.title(\"Box Plot cho tỷ lệ pixel màu trắng của các bức ảnh PNG chưa qua xử lý\")\n    plt.grid()\n\n    # Hiển thị box plot\n    plt.tight_layout()\n    plt.show()\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện biểu đồ phân bố mức ảnh đen, trắng của các bức ảnh đã qua xử lý\n!pip install torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch  # Nhập khẩu thư viện torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo_clahe/'\n\n# Danh sách để lưu tỷ lệ pixel đen và trắng\nblack_pixel_ratios = []\nwhite_pixel_ratios = []\n\n# Hàm tính tỷ lệ pixel đen và trắng cho một file PNG\ndef calculate_pixel_ratios(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n            \n            # Tính số lượng pixel đen và trắng\n            total_pixels = image_data.size\n            black_pixels = np.sum(image_data == 0)  # Số pixel có giá trị 0 (đen)\n            white_pixels = np.sum(image_data == 255)  # Số pixel có giá trị 255 (trắng)\n            \n            # Tính tỷ lệ\n            black_pixel_ratio = black_pixels / total_pixels\n            white_pixel_ratio = white_pixels / total_pixels\n            \n            return black_pixel_ratio, white_pixel_ratio\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None, None\n    return None, None\n\n# Sử dụng ThreadPoolExecutor để tính toán tỷ lệ pixel song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_pixel_ratios, os.listdir(png_dir)))\n\n# Lọc ra các tỷ lệ không phải là None\nfor result in results:\n    if result is not None:\n        black_pixel_ratios.append(result[0])\n        white_pixel_ratios.append(result[1])\n\n# Kiểm tra nếu danh sách không rỗng\nif black_pixel_ratios and white_pixel_ratios:\n    # Vẽ biểu đồ phân bố tỷ lệ pixel tối đen\n    plt.figure(figsize=(10, 6))\n    plt.hist(black_pixel_ratios, bins=30, color='blue', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Tỷ lệ pixel màu đen\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố tỷ lệ pixel màu đen của các bức ảnh PNG da qua xử lý can bang\")\n    plt.grid()\n    \n    # Hiển thị biểu đồ histogram\n    plt.tight_layout()\n    plt.show()\n\n    # Vẽ biểu đồ phân bố tỷ lệ pixel tối trắng\n    plt.figure(figsize=(10, 6))\n    plt.hist(white_pixel_ratios, bins=30, color='green', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Tỷ lệ pixel màu trắng\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố tỷ lệ pixel màu trắng của các bức ảnh PNG da qua xử lý can bang\")\n    plt.grid()\n    \n    # Hiển thị biểu đồ histogram\n    plt.tight_layout()\n    plt.show()\n\n    # Vẽ box plot cho tỷ lệ pixel tối đen\n    plt.figure(figsize=(10, 6))\n    plt.boxplot(black_pixel_ratios, vert=False, patch_artist=True, boxprops=dict(facecolor='lightblue'))\n    plt.xlabel(\"Tỷ lệ pixel màu đen\")\n    plt.title(\"Box Plot cho tỷ lệ pixel màu đen của các bức ảnh PNG da qua xử lý can bang\")\n    plt.grid()\n\n    # Hiển thị box plot\n    plt.tight_layout()\n    plt.show()\n\n    # Vẽ box plot cho tỷ lệ pixel tối trắng\n    plt.figure(figsize=(10, 6))\n    plt.boxplot(white_pixel_ratios, vert=False, patch_artist=True, boxprops=dict(facecolor='lightgreen'))\n    plt.xlabel(\"Tỷ lệ pixel màu trắng\")\n    plt.title(\"Box Plot cho tỷ lệ pixel màu trắng của các bức ảnh PNG da qua xử lý can bang\")\n    plt.grid()\n\n    # Hiển thị box plot\n    plt.tight_layout()\n    plt.show()\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện biểu đồ phân bố mức ảnh xám của các bức ảnh đã qua xử lý\n!pip install torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image\nimport torch  # Nhập khẩu thư viện torch\n\n# Kiểm tra xem TPU, GPU hay CPU có sẵn không\ndevice = 'cpu'\nif torch.cuda.is_available():\n    device = 'cuda'  # Sử dụng GPU\n    print('=======Sử dụng GPU=======')\nelif 'TPU_NAME' in os.environ:  # Kiểm tra xem TPU có sẵn không\n    device = 'tpu'  # Sử dụng TPU\n    print('=======Sử dụng TPU=======')\n\n# Đường dẫn đến thư mục chứa các file PNG\npng_dir = '/kaggle/input/vinbig-1024/train_png_1024_yolo_clahe/'\n\n# Danh sách để lưu tỷ lệ pixel có giá trị 128\npixel_128_ratios = []\n\n# Hàm tính tỷ lệ pixel có giá trị 128 cho một file PNG\ndef calculate_pixel_128_ratio(png_file):\n    png_path = os.path.join(png_dir, png_file)\n    if png_file.endswith('.png'):\n        try:\n            image = Image.open(png_path).convert('L')  # Chuyển đổi sang ảnh xám\n            image_data = np.array(image)\n            \n            # Tính số lượng pixel có giá trị 128\n            total_pixels = image_data.size\n            pixel_128_count = np.sum(image_data == 128)  # Số pixel có giá trị 128\n            \n            # Tính tỷ lệ\n            pixel_128_ratio = pixel_128_count / total_pixels if total_pixels > 0 else 0\n            return pixel_128_ratio\n        except Exception as e:\n            print(f\"Error reading {png_file}: {e}\")\n            return None\n    return None\n\n# Sử dụng ThreadPoolExecutor để tính toán tỷ lệ pixel có giá trị 128 song song\nwith ThreadPoolExecutor(max_workers=64) as executor:\n    results = list(executor.map(calculate_pixel_128_ratio, os.listdir(png_dir)))\n\n# Lọc ra các tỷ lệ không phải là None\npixel_128_ratios = [ratio for ratio in results if ratio is not None]\n\n# Kiểm tra nếu danh sách không rỗng\nif pixel_128_ratios:\n    # Vẽ biểu đồ phân bố tỷ lệ pixel có giá trị 128\n    plt.figure(figsize=(10, 6))\n    plt.hist(pixel_128_ratios, bins=30, color='blue', alpha=0.7, edgecolor='black')\n    plt.xlabel(\"Tỷ lệ pixel có giá trị xám trung bình\")\n    plt.ylabel(\"Số lượng ảnh\")\n    plt.title(\"Biểu đồ phân bố tỷ lệ pixel có giá trị xám trung bình trong các bức ảnh PNG da qua xu ly can bang\")\n    plt.grid()\n    \n    # Hiển thị biểu đồ histogram\n    plt.tight_layout()\n    plt.show()\n\n    # Vẽ box plot cho tỷ lệ pixel có giá trị 128\n    plt.figure(figsize=(10, 6))\n    plt.boxplot(pixel_128_ratios, vert=False, patch_artist=True, boxprops=dict(facecolor='lightblue'))\n    plt.xlabel(\"Tỷ lệ pixel có giá trị xám trung bình\")\n    plt.title(\"Box Plot cho tỷ lệ pixel có giá trị xám trung bình trong các bức ảnh PNG da qua xu ly can bang\")\n    plt.grid()\n\n    # Hiển thị box plot\n    plt.tight_layout()\n    plt.show()\nelse:\n    print(\"Không tìm thấy file PNG nào trong thư mục.\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện phân bố các mẫu ảnh qua 4 lớp được chọn, các mẫu ảnh này chưa qua xử lý tăng cường\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Đường dẫn đến tệp CSV\nfile_path = '/kaggle/input/vinbig-1024/train_png_1024_yolo.csv'\n\n# Đọc dữ liệu từ tệp CSV\ntrain_data = pd.read_csv(file_path)\n\n# Lọc dữ liệu chỉ bao gồm các class_id cần thiết\nfiltered_data = train_data[train_data['class_id'].isin([0, 3, 11, 13])]\n\n# Thống kê số lượng mẫu cho từng class_id\nclass_counts = filtered_data['class_id'].value_counts().reset_index()\nclass_counts.columns = ['class_id', 'count']\n\n# Thêm tên lớp tương ứng nếu có trong dữ liệu\nif 'class_name' in train_data.columns:\n    class_counts = class_counts.merge(filtered_data[['class_id', 'class_name']].drop_duplicates(), on='class_id')\n\n# In bảng thống kê\nprint(\"Số lượng mẫu của mỗi phân loại:\")\nprint(class_counts)\n\n# Vẽ biểu đồ Bar Chart\nplt.figure(figsize=(12, 8))\nsns.barplot(data=class_counts, x='class_id', y='count', palette='tab20')\nplt.title('Biểu đồ phân bố số mẫu trong mỗi phân loại', fontsize=16)\nplt.xlabel('Class ID', fontsize=14)\nplt.ylabel('Số lượng mẫu', fontsize=14)\n\n# Thêm số lượng mẫu lên trên các cột\nfor i, row in class_counts.iterrows():\n    plt.text(i, row['count'], f\"{row['count']}\", ha='center', va='bottom', fontsize=12)\n\nplt.show()\n\n# Vẽ biểu đồ Pie Chart\nif 'class_name' in class_counts.columns:\n    labels = class_counts['class_name']\nelse:\n    labels = class_counts['class_id']\n\nplt.figure(figsize=(8, 8))\nplt.pie(class_counts['count'], labels=labels, autopct='%1.1f%%', startangle=140, colors=sns.color_palette('tab20'))\nplt.title('Biểu đồ phân bố số mẫu theo phân loại', fontsize=16)\nplt.show()\n\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chương trình thể hiện phân bố các mẫu ảnh qua 4 lớp được chọn, các mẫu ảnh này đã được xử lý tăng cường ảnh\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Đường dẫn đến tệp CSV\nfile_path = '/kaggle/input/vinbig-1024/train_png_1024_yolo_clahe_flip.csv'\n\n# Đọc dữ liệu từ tệp CSV\ntrain_data = pd.read_csv(file_path)\n\n# Lọc dữ liệu chỉ bao gồm các class_id cần thiết\nfiltered_data = train_data[train_data['class_id'].isin([0, 3, 11, 13])]\n\n# Thống kê số lượng mẫu cho từng class_id\nclass_counts = filtered_data['class_id'].value_counts().reset_index()\nclass_counts.columns = ['class_id', 'count']\n\n# Thêm tên lớp tương ứng nếu có trong dữ liệu\nif 'class_name' in train_data.columns:\n    class_counts = class_counts.merge(filtered_data[['class_id', 'class_name']].drop_duplicates(), on='class_id')\n\n# In bảng thống kê\nprint(\"Số lượng mẫu của mỗi phân loại:\")\nprint(class_counts)\n\n# Vẽ biểu đồ Bar Chart\nplt.figure(figsize=(12, 8))\nsns.barplot(data=class_counts, x='class_id', y='count', palette='tab20')\nplt.title('Biểu đồ phân bố số mẫu trong mỗi phân loại', fontsize=16)\nplt.xlabel('Class ID', fontsize=14)\nplt.ylabel('Số lượng mẫu', fontsize=14)\n\n# Thêm số lượng mẫu lên trên các cột\nfor i, row in class_counts.iterrows():\n    plt.text(i, row['count'], f\"{row['count']}\", ha='center', va='bottom', fontsize=12)\n\nplt.show()\n\n# Vẽ biểu đồ Pie Chart\nif 'class_name' in class_counts.columns:\n    labels = class_counts['class_name']\nelse:\n    labels = class_counts['class_id']\n\nplt.figure(figsize=(8, 8))\nplt.pie(class_counts['count'], labels=labels, autopct='%1.1f%%', startangle=140, colors=sns.color_palette('tab20'))\nplt.title('Biểu đồ phân bố số mẫu theo phân loại', fontsize=16)\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}