Skip to content

Instantly share code, notes, and snippets.

@vinothpandian
Created January 22, 2022 16:42
Show Gist options
  • Save vinothpandian/0bbeed954dade522d020d04186f7b6f2 to your computer and use it in GitHub Desktop.
Save vinothpandian/0bbeed954dade522d020d04186f7b6f2 to your computer and use it in GitHub Desktop.
center_crop_pytorch.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "center_crop_pytorch.ipynb",
"private_outputs": true,
"provenance": [],
"collapsed_sections": [],
"authorship_tag": "ABX9TyNZKjQBZ+CftFRO+N5GNybc",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/vinothpandian/0bbeed954dade522d020d04186f7b6f2/center_crop_pytorch.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9PqgsCzeUEO7"
},
"outputs": [],
"source": [
"import torch\n",
"import torchvision\n",
"\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "code",
"source": [
"dataset = torchvision.datasets.FashionMNIST(\n",
" root=\"data\",\n",
" train=True,\n",
" download=True,\n",
" transform=torchvision.transforms.ToTensor()\n",
")\n",
"\n",
"dataloader = torch.utils.data.DataLoader(dataset, batch_size=8, shuffle=True)"
],
"metadata": {
"id": "OYkjwV-vke_7"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"img_batch, _ = next(iter(dataloader))"
],
"metadata": {
"id": "ebBok7Vil1lM"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def show_grid(img_batch):\n",
" print(img_batch.shape)\n",
" img = torchvision.utils.make_grid(img_batch, nrow=4)\n",
" plt.imshow(img.permute(1, 2, 0))"
],
"metadata": {
"id": "A8TDRXvamBXt"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"show_grid(img_batch)"
],
"metadata": {
"id": "DHIrkDaJnueG"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Center crop image"
],
"metadata": {
"id": "RindpqrRe7yx"
}
},
{
"cell_type": "code",
"source": [
"center_cropped_img_batch = torchvision.transforms.functional.center_crop(img_batch, 14)\n",
"show_grid(center_cropped_img_batch)"
],
"metadata": {
"id": "ZcamZmd1edAp"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"transform = torchvision.transforms.CenterCrop(14)\n",
"show_grid(transform(img_batch))"
],
"metadata": {
"id": "UmWwRG6XqITZ"
},
"execution_count": null,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment