easy-gradcam


Nameeasy-gradcam JSON
Version 0.0.2 PyPI version JSON
download
home_pageNone
SummaryGradCAM for torchvision, timm and huggingface model.
upload_time2025-09-12 08:37:15
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT License Copyright (c) 2025 Po-Yung Chou Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords easy to use(i hope) gradcam
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # easy_gradcam

A lightweight tool to generate Grad-CAM visualizations for image classification models.
It supports popular backbones such as **ResNet**, **Vision Transformers (ViT)**, and **Hugging Face Transformers**.

---

## Installation

```bash
pip install easy_gradcam
```

## Quick Start

### 1. Import dependencies
```python
import cv2
import torchvision.models as models
import torchvision.transforms as transforms
import timm
from transformers import AutoModelForImageClassification
from easy_gradcam.classification import EasyGradCAM
from easy_gradcam.visualization import save_heatmap, save_mix_heatmap
```

### 2. Load a model
You can use different backbones:
```python
# Example 1: ResNet-50 (torchvision)
model = models.resnet50(pretrained=True)   # targets: "layer4"

# Example 2: ViT (timm)
model = timm.create_model("vit_base_patch16_224_miil", pretrained=True)   # targets: "blocks.10"

# Example 3: Hugging Face (DINOv2)
model = AutoModelForImageClassification.from_pretrained(
    "facebook/dinov2-small-imagenet1k-1-layer"
) # targets: "dinov2.encoder.layer.11"
model.eval()

```

### 3. Prepare an image
```python
img = cv2.imread("./exp1.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

totensor = transforms.ToTensor()
resize = transforms.Resize((224, 224))
normalize = transforms.Normalize([0.485, 0.456, 0.406],
                                 [0.229, 0.224, 0.225])

t = totensor(img)
t = resize(t)
t = normalize(t)
t = t.unsqueeze(0)  # add batch dimension

```

### 4. Compute Grad-CAM
```python
gradcam = EasyGradCAM(model, targets="dinov2.encoder.layer.11")

# Extract features and gradients
feats, grads = gradcam.cal_feat_and_grad(t)

# Generate heatmaps
heats = gradcam.cal_heats(img, feats, grads)
```

### 5. Save results
```python
for i in range(len(heats)):
    for name in heats[i]:
        # Save plain heatmap
        save_heatmap(
            save_path=f"results/{i}-{name}.jpg",
            heat=heats[i][name],
            cmap="jet",
            title="grad-cam"
        )

        # Save overlay with original image
        save_mix_heatmap(
            save_path=f"results/{i}-{name}-mix.jpg",
            heat=heats[i][name],
            ori_img=img,
            cmap="jet"
        )
```

### Example Output
- results/0-dinov2.encoder.layer.11.jpg: heatmap only
<img src="https://hackmd-prod-images.s3-ap-northeast-1.amazonaws.com/uploads/upload_a05f1eddb8ad02fdf6b4a4e4ba804ecc.jpg?AWSAccessKeyId=AKIA3XSAAW6AWSKNINWO&Expires=1757664967&Signature=C6D2nHzRjvJ6WAKpUZdjeSZ4Rzw%3D" width="400">

- results/0-dinov2.encoder.layer.11-mix.jpg: heatmap overlay on the input image
<img src="https://hackmd-prod-images.s3-ap-northeast-1.amazonaws.com/uploads/upload_a3749220bab545262528304ae6542148.jpg?AWSAccessKeyId=AKIA3XSAAW6AWSKNINWO&Expires=1757664978&Signature=rMiL%2BcLtmqti5tE2dPfQQskrVGU%3D" width="400">

### Notes
* Make sure the target layer you pass matches the internal structure of the model.
* Pretrained models from torchvision, timm, and Hugging Face are supported.
* Heatmaps are saved as .jpg files in the results/ directory.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "easy-gradcam",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "easy to use(I hope), gradcam",
    "author": null,
    "author_email": "PoYung Chou <ball60304@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/ea/c2/f7c911897021b096a6ebfd9da8a7deab5a8c1d109e17807f35bd36059462/easy_gradcam-0.0.2.tar.gz",
    "platform": null,
    "description": "# easy_gradcam\r\n\r\nA lightweight tool to generate Grad-CAM visualizations for image classification models.\r\nIt supports popular backbones such as **ResNet**, **Vision Transformers (ViT)**, and **Hugging Face Transformers**.\r\n\r\n---\r\n\r\n## Installation\r\n\r\n```bash\r\npip install easy_gradcam\r\n```\r\n\r\n## Quick Start\r\n\r\n### 1. Import dependencies\r\n```python\r\nimport cv2\r\nimport torchvision.models as models\r\nimport torchvision.transforms as transforms\r\nimport timm\r\nfrom transformers import AutoModelForImageClassification\r\nfrom easy_gradcam.classification import EasyGradCAM\r\nfrom easy_gradcam.visualization import save_heatmap, save_mix_heatmap\r\n```\r\n\r\n### 2. Load a model\r\nYou can use different backbones:\r\n```python\r\n# Example 1: ResNet-50 (torchvision)\r\nmodel = models.resnet50(pretrained=True)   # targets: \"layer4\"\r\n\r\n# Example 2: ViT (timm)\r\nmodel = timm.create_model(\"vit_base_patch16_224_miil\", pretrained=True)   # targets: \"blocks.10\"\r\n\r\n# Example 3: Hugging Face (DINOv2)\r\nmodel = AutoModelForImageClassification.from_pretrained(\r\n    \"facebook/dinov2-small-imagenet1k-1-layer\"\r\n) # targets: \"dinov2.encoder.layer.11\"\r\nmodel.eval()\r\n\r\n```\r\n\r\n### 3. Prepare an image\r\n```python\r\nimg = cv2.imread(\"./exp1.jpg\")\r\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n\r\ntotensor = transforms.ToTensor()\r\nresize = transforms.Resize((224, 224))\r\nnormalize = transforms.Normalize([0.485, 0.456, 0.406],\r\n                                 [0.229, 0.224, 0.225])\r\n\r\nt = totensor(img)\r\nt = resize(t)\r\nt = normalize(t)\r\nt = t.unsqueeze(0)  # add batch dimension\r\n\r\n```\r\n\r\n### 4. Compute Grad-CAM\r\n```python\r\ngradcam = EasyGradCAM(model, targets=\"dinov2.encoder.layer.11\")\r\n\r\n# Extract features and gradients\r\nfeats, grads = gradcam.cal_feat_and_grad(t)\r\n\r\n# Generate heatmaps\r\nheats = gradcam.cal_heats(img, feats, grads)\r\n```\r\n\r\n### 5. Save results\r\n```python\r\nfor i in range(len(heats)):\r\n    for name in heats[i]:\r\n        # Save plain heatmap\r\n        save_heatmap(\r\n            save_path=f\"results/{i}-{name}.jpg\",\r\n            heat=heats[i][name],\r\n            cmap=\"jet\",\r\n            title=\"grad-cam\"\r\n        )\r\n\r\n        # Save overlay with original image\r\n        save_mix_heatmap(\r\n            save_path=f\"results/{i}-{name}-mix.jpg\",\r\n            heat=heats[i][name],\r\n            ori_img=img,\r\n            cmap=\"jet\"\r\n        )\r\n```\r\n\r\n### Example Output\r\n- results/0-dinov2.encoder.layer.11.jpg: heatmap only\r\n<img src=\"https://hackmd-prod-images.s3-ap-northeast-1.amazonaws.com/uploads/upload_a05f1eddb8ad02fdf6b4a4e4ba804ecc.jpg?AWSAccessKeyId=AKIA3XSAAW6AWSKNINWO&Expires=1757664967&Signature=C6D2nHzRjvJ6WAKpUZdjeSZ4Rzw%3D\" width=\"400\">\r\n\r\n- results/0-dinov2.encoder.layer.11-mix.jpg: heatmap overlay on the input image\r\n<img src=\"https://hackmd-prod-images.s3-ap-northeast-1.amazonaws.com/uploads/upload_a3749220bab545262528304ae6542148.jpg?AWSAccessKeyId=AKIA3XSAAW6AWSKNINWO&Expires=1757664978&Signature=rMiL%2BcLtmqti5tE2dPfQQskrVGU%3D\" width=\"400\">\r\n\r\n### Notes\r\n* Make sure the target layer you pass matches the internal structure of the model.\r\n* Pretrained models from torchvision, timm, and Hugging Face are supported.\r\n* Heatmaps are saved as .jpg files in the results/ directory.\r\n",
    "bugtrack_url": null,
    "license": "MIT License\r\n        \r\n        Copyright (c) 2025 Po-Yung Chou\r\n        \r\n        Permission is hereby granted, free of charge, to any person obtaining a copy\r\n        of this software and associated documentation files (the \"Software\"), to deal\r\n        in the Software without restriction, including without limitation the rights  \r\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell  \r\n        copies of the Software, and to permit persons to whom the Software is  \r\n        furnished to do so, subject to the following conditions:\r\n        \r\n        The above copyright notice and this permission notice shall be included in all  \r\n        copies or substantial portions of the Software.\r\n        \r\n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  \r\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  \r\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  \r\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  \r\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  \r\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  \r\n        SOFTWARE.",
    "summary": "GradCAM for torchvision, timm and huggingface model.",
    "version": "0.0.2",
    "project_urls": null,
    "split_keywords": [
        "easy to use(i hope)",
        " gradcam"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3b60365f08b7288ea1595cbc23b38bf04d0f6232bb74783db8f5a2deac96af68",
                "md5": "fde596bc1a939cf0c2dee0f85d6043e6",
                "sha256": "001310611103c76785cae0948c449818b643622a9fb2b66881292384a0171938"
            },
            "downloads": -1,
            "filename": "easy_gradcam-0.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fde596bc1a939cf0c2dee0f85d6043e6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 7749,
            "upload_time": "2025-09-12T08:37:14",
            "upload_time_iso_8601": "2025-09-12T08:37:14.209707Z",
            "url": "https://files.pythonhosted.org/packages/3b/60/365f08b7288ea1595cbc23b38bf04d0f6232bb74783db8f5a2deac96af68/easy_gradcam-0.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "eac2f7c911897021b096a6ebfd9da8a7deab5a8c1d109e17807f35bd36059462",
                "md5": "50aff9c2c2376b9125e01e3107144f65",
                "sha256": "4cc89c7d4888299bd861103abc41671104c2150a74543d9f004db2c8003f5607"
            },
            "downloads": -1,
            "filename": "easy_gradcam-0.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "50aff9c2c2376b9125e01e3107144f65",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 7456,
            "upload_time": "2025-09-12T08:37:15",
            "upload_time_iso_8601": "2025-09-12T08:37:15.581277Z",
            "url": "https://files.pythonhosted.org/packages/ea/c2/f7c911897021b096a6ebfd9da8a7deab5a8c1d109e17807f35bd36059462/easy_gradcam-0.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-12 08:37:15",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "easy-gradcam"
}
        
Elapsed time: 2.20650s