Lorrayya Williams
Lorrayya Williams

Reputation: 3

Converting color images to a grayscale images

I am using the pets dataset. I want to convert those images to grayscale, but I have no idea how and haven't found many useful things from looking through the internet. If someone could point me in the right direction, so I can figure out how to either change it to a one channel image or grayscale that would be great.

from fastai.vision.all import *
set_seed(333)
image_files = get_image_files(path).sorted().shuffle()
splitter = RandomSplitter(valid_pct=0.2, seed=42)
dblock = DataBlock(blocks    = (ImageBlock, CategoryBlock),
                   get_y     = get_y,
                   splitter  = splitter,
                   item_tfms = Resize(224))
dataloaders = dblock.dataloaders(image_files, batch_size=9, shuffle_fn=lambda idxs: idxs)
batch = dataloaders.train.one_batch()
images, labels = batch
show_image_batch((images, labels))

Upvotes: 0

Views: 865

Answers (1)

Fred Guth
Fred Guth

Reputation: 1667

You can specify the type of the image in a DataBlock: ImageBlock(cls=PILImageBW

from fastai.vision.all import *
set_seed(333)
path = untar_data(URLs.PETS)/"images"
image_files = get_image_files(path)
splitter = RandomSplitter(valid_pct=0.2, seed=42)
dblock = DataBlock(blocks    = (ImageBlock(cls=PILImageBW), CategoryBlock),
                   get_y     = lambda x: re.match(r'^(.*)_\d+.jpg$', x.name).groups()[0],
                   splitter  = splitter,
                   item_tfms = [Resize(224)],
                  )

dataloaders = dblock.dataloaders(image_files, batch_size=9)
dataloaders.show_batch()

show_batch

Alternatively, you can apply any transform you like to your dataloaders after_batch.

Upvotes: 1

Related Questions