Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

request for adding 4 bands-image training #8405

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added test/assets/folder_test_img/cat.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added test/assets/folder_test_img/ortho_crop.tif
Binary file not shown.
38 changes: 38 additions & 0 deletions test/test_folder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
"""
Created on Fri May 3 17:45:10 2024

@author: tohya

file: test_folder.py
"""

from PIL import Image
import numpy as np

def test_pil_loader(path: str) -> Image.Image:
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, "rb") as f:
img = Image.open(f)
if(len(Image.Image.getbands(img))!=4):
img=img.convert("RGB")
else:
img=img.convert("RGBX") # in case RGBN(RGB,NIR)
return img


if __name__ == "__main__":

file1 = "assets/folder_test_img/cat.jpg"
file2 = "assets/folder_test_img/ortho_crop.tif"

img1 = test_pil_loader(file1)
shape1 = np.array(img1).shape

img2 = test_pil_loader(file2)
shape2 = np.array(img2).shape

print(f"3 bands jpeg image(RBG) shape: {shape1}")
print(f"4 bands tiff image(RGBN) shape: {shape2}")


5 changes: 4 additions & 1 deletion torchvision/datasets/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,10 +258,13 @@ def __len__(self) -> int:


def pil_loader(path: str) -> Image.Image:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was suggesting something like this. This would be backward compatible as the default conversion is RGB. And in special cases where we want the conversation to other color space, (like RGBX) in your case we could handle that as well. Basically a more generalised solution.

Suggested change
def pil_loader(path: str) -> Image.Image:
def pil_loader(path: str, convert_to="RGB") -> Image.Image:

conv = "RGB"
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, "rb") as f:
img = Image.open(f)
return img.convert("RGB")
if img.mode == "RGBX": # in case RGBN(RGB,NIR)
conv = "RGBX"
return img.convert(conv)


# TODO: specify the return type
Expand Down