optiminzer this code run in gpufrom torchvision import transformsimport torchimport cv2class ImagePreprocess def __init__self device=cpu selfnorm_image = transformsComposeScaleImage
To optimize this code to run on the GPU, we can make the following changes:
- Convert the numpy arrays to PyTorch tensors before sending them to the GPU.
- Use PyTorch's built-in image resizing and normalization functions instead of using OpenCV.
- Remove the unnecessary numpy operations.
Here's the optimized code:
from torchvision import transforms import torch
class ImagePreprocess: def init(self, device="cpu"): self.transform = transforms.Compose([ transforms.Resize((img_size, img_size)), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ]) self.device = device
def preprocess(self, imgs, img_size):
imgs_tensor = torch.stack([self.transform(img) for img in imgs]).to(self.device)
return imgs_tensor.cpu().detach().numpy()
Example usage
preprocessor = ImagePreprocess(device="cuda") imgs = [cv2.imread(img_path) for img_path in img_paths] preprocessed_imgs = preprocessor.preprocess(imgs, img_size=224)
原文地址: http://www.cveoy.top/t/topic/6pQ 著作权归作者所有。请勿转载和采集!