AttributeError: ‘torch.Size‘ object has no attribute ‘numpy‘

Project scenario:

提示:这里是图像-关键点标签,制作数据集生成器时的一个bug

Project scenario:
Image and label data production dataset generator:
During the preprocessing of the dataset, the size of the image needs to be changed, because the label data is a coordinate group and needs to be changed synchronously with the image. At this time, the ratio before and after the image change is used to calculate the result after the coordinate change. Since the image transformation used is the transforms transformation method in the transforms packaged by torchvision, the returned data is torch.Tensor. The returned size is torch.Size.
During operation, the function __getitem__reports an error:

def __getitem__(self, idx):
    img_id = self._image_paths[idx]
    img_id = os.path.join(self.root_dir, img_id)
    image = Image.open(img_id).convert('RGB')  # (宽,高,通道数)= (w, h, c)
    imgSize = image.size  # 原始图像宽高
    landmarks = np.asfortranarray(self._labels[idx])  # (x, y, 显隐)=(宽,高,显隐性)
    category = self._categories.index(self._cates[idx])  # 0,1,2,3,4

    if self.transform_img:
        image = self.transform_img(image)  # 返回torch.Size([3, 256, 256])
    else:
        image.resize((256, 256))  # 使用resize
    afterSize = image.shape[1:].numpy()  # 缩放后图像的宽高
    print(imgSize, afterSize)
    bi = afterSize / imgSize
    landmarks[:, 0:2] = landmarks[:, 0:2] * bi

    return image, landmarks, category

Error content:

File "E:/TanhaiyansCode/kpdem_with_pytorch/dataset/dataset_by_PIL.py", line 78, in __getitem__
    afterSize = image.shape[1:].numpy()  # 缩放后图像的宽高
AttributeError: 'torch.Size' object has no attribute 'numpy'


Problem Description

提示:这里描述项目中遇到的问题:

For example: data is lost from time to time during data transmission, and occasionally a part of the data is lost.
The code for receiving data in the APP:

@Override
	public void run() {
    
    
		bytes = mmInStream.read(buffer);
		mHandler.obtainMessage(READ_DATA, bytes, -1, buffer).sendToTarget();
	}

Cause Analysis:

Location error code:

 afterSize = image.shape[1:].numpy()  # 缩放后图像的宽高

error code:AttributeError: 'torch.Size' object has no attribute 'numpy'

image is torch.Tensor type, image.shape returns torch.Size, only torch.Tensor has numpy() method. So you need to put .numpy() behind the image to use it.

solution:

Only torch.Tensor has the numpy() method, so convert it to a numpy array first, and then take the size.

Code modification:

afterSize = image.numpy().shape[1:]  # 缩放后图像的宽高

Guess you like

Origin blog.csdn.net/beauthy/article/details/124867392