Use cv2 to load images in custom dataset

I wrote a custom dataset to upload images and it works correctly when I use PIL module. How can i use cv2 instead?

If I just try to read the image with

img = cv2.imread(file_path)

it throws the error
img should be PIL Image. Got <class 'numpy.ndarray'>
produced by the transform function (the PyTorch transformation from torchvision.transforms to be clear).

Any idea on how to solve?

Transforms are PIL based, thus, it only works with PIL. There exist a library called pillow-simd which is a drop-and-replace PILLOW library. It’s optimized and faster than native PIL.

After loading with opencv you can convert it to PIL image using
PIL.Image.fromarray( ) and then apply torchvision transforms

And if I want to upload the images using PIL library and then open them with cv2? Is it possible?
I tried, but I was not able to do that, since they seem to have a different format.

again you can use PIL to upload and convert img to numpy array.
Just check tha RGB format because cv2 loads image in BGR format by default