Why Python stops to work on GPU when using SimpleITK library in MONAI transforms? - anaconda

I'm using Python 3.9 with Spyder 5.2.2 (Anaconda) for a U-Net segmentation task with MONAI. After importing all the images in a dictionary, I create these lines to define pre-process steps:
import SimpleITK as sitk
from monai.inferers import SimpleInferer
from monai.transforms import (
AsDiscrete,
DataStatsd,
AddChanneld,
Compose,
Activations,
LoadImaged,
Resized,
RandFlipd,
ScaleIntensityRanged,
DataStats,
AsChannelFirstd,
AsDiscreted,
ToTensord,
EnsureTyped,
RepeatChanneld,
EnsureType
)
from monai.transforms import Transform
monai_load = [
LoadImaged(keys=["image","segmentation"],image_only=False,reader=PILReader()),
EnsureTyped(keys=["image", "segmentation"], data_type="numpy"),
AddChanneld(keys=["segmentation","image"]),
RepeatChanneld(keys=["image"],repeats=3),
AsChannelFirstd(keys=["image"], channel_dim = 0),
]
monai_transforms =[
AsDiscreted(keys=["segmentation"],threshold=0.5),
ToTensord(keys=["image","segmentation"]),
]
class N4ITKTransform(Transform):
def __call__(self,image):
filtered = []
for channel in image["image"]:
inputImage = sitk.GetImageFromArray(channel)
inputImage = sitk.Cast(inputImage, sitk.sitkFloat32)
corrector = sitk.N4BiasFieldCorrectionImageFilter()
outputImage = corrector.Execute(inputImage)
filtered.append(sitk.GetArrayFromImage(outputImage))
image["image"] = np.stack(filtered)
return image
train_transforms = Compose(monai_load + [N4ITKTransform()] + monai_transforms)
When i recall these transforms with Compose and apply them to the train images, python does not work on GPU despite
torch.cuda.is_available()
return True.
These are the lines where I apply the transforms:
train_ds = IterableDataset(data = train_data, transform = train_transforms)
train_loader = DataLoader(dataset = train_ds, batch_size = batch_size, num_workers = 0, pin_memory = True)
When I define the U-Net model, I send it to 'cuda'.
The problem is in the SimpleITK transform. If I don't use them, Python works on GPU as usual.
Thank you in advance for getting back to me.
Federico

The answer is simple: SimpleITK uses CPU for processing.
I am not sure whether it is possible to get it to use some of the GPU-accelerated filters from ITK (its base library). If you use ITK Python, you have the possibility to use GPU-filters. But only a few filters have GPU implementations. N4BiasFieldCorrection does NOT have a GPU implementation. So if you want to use this filter, it needs to be done on the CPU.

Related

Python 3.8 SharedMemory performance

I'm trying to use SharedMemory introduced in Python 3.8 to pass images between processes. According to my test below, writing the image to memory took around 9ms on my Ubuntu machine. I'm wondering if there are any ways to make this even faster?
import numpy as np
import time
from multiprocessing import shared_memory
queue_name = "queue"
image = np.zeros((2464, 2056, 3), dtype=np.uint8)
queue_size = 10
shared_memory_size = queue_size * np.prod(image.shape)
sm = shared_memory.SharedMemory(name=queue_name, create=True, size=shared_memory_size)
images = np.ndarray([queue_size] + list(image.shape), dtype=np.uint8, buffer=sm.buf)
t0 = time.perf_counter()
images[0] = image.data
print(time.perf_counter() - t0)

open3d voxel_size too small : down sampling not working for e57 binaries

I'm trying to downsample a point cloud. I have 2 data formats for different parts of my data.
The .bin files cause no problems, but when I'm trying to downsample the .e57 files I encounter a strange problem.
Here's what I do:
import numpy as np
import open3d
pointfile = "path/to/file.e57"
pcd_data = np.fromfile(point_file, dtype=np.float32)
pcd_data = velo_data.reshape(-1, 4)
pcd_points = velo_data[:, :3]
pcd = open3d.geometry.PointCloud()
pcd.points = open3d.utility.Vector3dVector(pcd_points)
pcd_down = pcd.voxel_down_sample(voxel_size=0.8)
res = np.asarray(pcd_down.points)
It works fine for .bin, but when i try the .e57 I get the error:
RuntimeError: [Open3D ERROR] [VoxelDownSample] voxel_size is too small.
No matter if I use voxel_size of 0.005, 0.8, 100, 5000 or 1000000000000000.
I tried the earlier open3d Version:
pcd_down = open3d.geometry.voxel_down_sample(voxel_size=0.8)
and at least it throws no error, but my downsampled pointcloud then contains 0 points (from ~350 000).
As the file should be structured in points with 4 features, the file seems to be read correctly (this works for any of my files), as the reshape works just fine.
Any ideas?
Still have no clue about the original error, but I succesfully worked around the problem by using pye57:
https://github.com/davidcaron/pye57
together with this solution to a possibly occuring problem:
https://github.com/davidcaron/pye57/issues/6#issuecomment-803894677
With this code
import numpy as np
import open3d
import pye57
point_file = "path/to/file.e57"
e57 = pye57.E57(point_file)
data = e57.read_scan_raw(0)
assert isinstance(data["cartesianX"], np.ndarray)
assert isinstance(data["cartesianY"], np.ndarray)
assert isinstance(data["cartesianZ"], np.ndarray)
x = np.array(data["cartesianX"])
y = np.array(data["cartesianY"])
z = np.array(data["cartesianZ"])
pcd_points = np.concatenate((x, y), axis=0)
pcd_points = np.concatenate((pcd_points, z), axis=0)
pcd_points = velo_points.reshape(-1, 3)
pcd = open3d.geometry.PointCloud()
pcd.points = open3d.utility.Vector3dVector(pcd_points)
pcd_down = pcd.voxel_down_sample(voxel_size=0.0035)
I finally get a downsampled point cloud.

Pytorch: load dataset of grayscale images

I want to load a dataset of grayscale images. I used ImageFolder but this doesn't load gray images by default as it converts images to RGB.
I found solutions that load images with ImageFolder and after convert images in grayscale, using:
transforms.Grayscale(num_output_channels=1)
or
ImageOps.grayscale(image)
Is it correct?
How can I load grayscale imaged without conversion? I try ImageDataBunch, but I have problems to import fastai.vision
Assuming the dataset is stored in the "Dataset" folder as given below, set the root directory as "Dataset":
Dataset
class_1
img1.png
img2.png
class_2
img1.png
img2.png
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader, random_split
from torchvision import transforms
root = 'Dataset/'
data_transform = transforms.Compose([transforms.Grayscale(num_output_channels=1),
transforms.ToTensor()])
dataset = ImageFolder(root, transform=data_transform)
For reference, train and test dataset are being split into 70% and 30% respectively.
# Split test and train dataset
train_size = int(0.7 * len(dataset))
test_size = len(dataset) - train_size
train_data, test_data = random_split(dataset, [train_size, test_size])
This dataset can be further divided into train and test data loaders as given below to perform operation in batches.
Usually you will see the dataset is assigned batch_size once to be used for both train and test loaders. But, I try to define it separately. The idea is to give the batch_size such that it is a factor of the train/test data loader's size, otherwise it will give an error.
# Set batch size of train data loader
batch_size_train = 20
# Set batch size of test data loader
batch_size_test = 22
# load the split train and test data into batches via DataLoader()
train_loader = DataLoader(train_data, batch_size=batch_size_train, shuffle=True)
test_loader = DataLoader(test_data, batch_size=batch_size_test, shuffle=True)
Yes, that is correct and AFAIK pillow by default loads images in RGB, see e.g. answers to this question. So conversion to grayscale is the only way, though takes time of course.
Pure pytorch solution (if ImageFolder isn't appropriate)
You can roll out your own data loading functionalities and If I were you I wouldn't go fastai route as it's pretty high level and takes away control from you (you might not need those functionalities anyway).
In principle, all you have to do is to create something like this below:
import pathlib
import torch
from PIL import Image
class ImageDataset(torch.utils.data.Dataset):
def __init__(self, path: pathlib.Path, images_class: int, regex="*.png"):
self.files = [file for file in path.glob(regex)]
self.images_class: int = images_class
def __getitem__(self, index):
return Image.open(self.files[index]).convert("LA"), self.images_class
# Assuming you have `png` images, can modify that with regex
final_dataset = (
ImageDataset(pathlib.Path("/path/to/dogs/images"), 0)
+ ImageDataset(pathlib.Path("/path/to/cats/images"), 1)
+ ImageDataset(pathlib.Path("/path/to/turtles/images"), 2)
)
Above would get you images from the paths provided above and each image would return appropriate provided class.
This gives you more flexibility (different folder setting than torchvision.datasets.ImageFolder) for a few more lines.
Ofc, you could add more of those or use loop or whatever else.
You could also apply torchvision.transforms, e.g. transforming images above to tensors, read
torchdata solution
Disclaimer, author here. If you are cocerned about loading times of your data and grayscale transformation you could use torchdata third party library for pytorch.
Using it one could create the same thing as above but use cache or map (to use torchvision.transforms or other transformations easily) and some other things known e.g. from tensorflow.data module, see below:
import pathlib
from PIL import Image
import torchdata
# Change inheritance
class ImageDataset(torchdata.Dataset):
def __init__(self, path: pathlib.Path, images_class: int, regex="*.png"):
super().__init__() # And add constructor call and that's it
self.files = [file for file in path.glob(regex)]
self.images_class: int = images_class
def __getitem__(self, index):
return Image.open(self.files[index]), self.images_class
final_dataset = (
ImageDataset(pathlib.Path("/path/to/dogs/images"), 0)
+ ImageDataset(pathlib.Path("/path/to/cats/images"), 1)
+ ImageDataset(pathlib.Path("/path/to/turtles/images"), 2)
).cache() # will cache data in-memory after first pass
# You could apply transformations after caching for possible speed-up
torchvision ImageFolder loader
As correctly pointed out by #jodag in the comments, one can use loader callable with single argument path to do customized data opening, e.g. for grayscale it could be:
from PIL import Image
import torchvision
dataset = torchvision.datasets.ImageFolder(
"/path/to/images", loader=lambda path: Image.open(path).convert("LA")
)
Please notice you could also use it for other types of files, those doesn't have to be images.
Make custom loader, feed it to ImageFolder:
import numpy as np
from PIL import Image, ImageOps
def gray_reader(image_path):
im = Image.open(image_path)
im2 = ImageOps.grayscale(im)
im.close()
return np.array(im2) # return np array
# return im2 # return PIL Image
some_dataset = ImageFolder(image_root_path, loader=gray_reader)
Edit:
Below code is much better than previous, get color image and convert to grayscale in transform()
def get_transformer(h, w):
valid_transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Grayscale(num_output_channels=1),
transforms.Resize((h, w)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]) ])
return valid_transform

Image registration with SimpleITK

I want to do multi-modality image registration(mri/ct) but I do not have completely aligned images, results obtained with simpleITK are very bad. Even if I try to align them, results are still ridiculously bad.
What can I do to fix this? My registration code is as follow:
import SimpleITK as sitk
def fusion(ct, mr):
fixed = sitk.GetImageFromArray(ct, isVector=True)
moving = sitk.GetImageFromArray(mr, isVector=True)
numberOfBins = 24
samplingPercentage = 0.10
R = sitk.ImageRegistrationMethod()
R.SetMetricAsMattesMutualInformation(numberOfBins)
R.SetMetricSamplingPercentage(samplingPercentage,sitk.sitkWallClock)
R.SetMetricSamplingStrategy(R.RANDOM)
R.SetOptimizerAsRegularStepGradientDescent(1.0,.001,200)
R.SetInitialTransform(sitk.TranslationTransform(fixed.GetDimension()))
R.SetInterpolator(sitk.sitkLinear)
#R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )
outTx = R.Execute(fixed, moving)
def get_result():
resampler = sitk.ResampleImageFilter()
resampler.SetReferenceImage(fixed);
resampler.SetInterpolator(sitk.sitkLinear)
resampler.SetDefaultPixelValue(100)
resampler.SetTransform(outTx)
out = resampler.Execute(moving)
simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)
cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)
return sitk.GetArrayFromImage(cimg)
#sitk.Show( cimg, "ImageRegi
return get_result()
I think you forgot to make an initial alignment of your images at the beginning.
trans = sitk.CenteredTransformInitializer(fixed ,moving, sitk.Euler3DTransform(), sitk.CenteredTransformInitializerFilter.GEOMETRY)

Pygame cannot load image from same directory as script

So I installed python 2.7.8 and the latest pygame, but I can't seem to get image.load () to find my image file, despite several attempts to rename and recheck the spelling. The image and script that use it are in the same directory. Has anyone run into similar issues?
self.src_image = pygame.image.load
Is the line in question. image is used as a parameter that is filled later with a specific file name.
Here is some context:
import pygame, math, sys, os
from pygame.locals import *
screen = pygame.display.set_mode((1024, 786))
clock = pygame.time.Clock()
class WitchSprite(pygame.sprite.Sprite):
speed = 10
acceleration = .4
def __init__(self, image, position):
pygame.sprite.Sprite.__init__(self)
self.src_image = pygame.image.load(os.path.join(image))
self.postion = position
self.speed = self.direction = 0
self.k_left = self.k_right = self.k_down = self.k_up = 0
First, check that your image can even be loaded. Use pygame.image.get_extended() to check if it will load image formats. It should return True.
The pygame docs say that you should "use os.path.join() for compatibility." Try to load your image using os and see if that takes care of your problem.
ex: "asurf = pygame.image.load(os.path.join('data', 'bla.png'))"

Resources