python - 如何处理 PyTorch 中图像字幕目录中的多标签数据集

标签 python pytorch

我需要 PyTorch 方面的帮助, 关于Dataloader和数据集 有人可以帮助/指导我

这是我的查询: 我正在尝试使用 https://github.com/yunjey/pytorch-tutorial/tree/master/tutorials/03-advanced/image_captioning 进行图像字幕.

这里他们使用了标准 COCO 数据集。

我的数据集为 images/和 Captions/目录。

示例

目录结构:

images/T001.jpg 
images/T002.jpg 
...
...
captions/T001.txt
captions/T002.txt
....
....

以上是关系。字幕文件的每行都有“n”个字幕。

我能够创建一个自定义数据集类,因为正在返回完整的标题文件内容。但我只想返回一根单独的气体。

关于如何实现这一目标的任何指导/建议。

++++++++++++++++++++++++++++++++++++++++++++++++++ + 这是我设计的类:

from __future__ import print_function
import torch
from torchvision import datasets, models, transforms
from torchvision import transforms
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
import torch.optim as optim
import torch.nn as nn
#from torch import np
import numpy as np
import utils_c
from data_loader_c import get_cust_data_loader 
from models import CNN, RNN
from vocab_custom import Vocabulary, load_vocab
import os

class ImageCaptionDataSet(data.Dataset):
    def __init__(self, path, json, vocab=None, transform=None):
        self.vocab = vocab 
        self.transform = transform
        self.img_dir_path = path  
        self.cap_dir_path = json 
        self.all_imgs_path = glob.glob(os.path.join(self.img_dir_path,'*.jpg'))
        self.all_caps_path = glob.glob(os.path.join(self.cap_dir_path,'*.txt'))
        pass

    def __getitem__(self,index):
        vocab = self.vocab

        img_path = self.all_imgs_path[index]
        img_base_name = os.path.basename(img_path) 
        cap_base_name = img_base_name.replace(".jpg",".txt")
        cap_path  = os.path.join(self.cap_dir_path,cap_base_name)

        caption_all_for_a_image = open(cap_path).read().split("\n")

        image = Image.open(img_path)
        image = image.convert('RGB')

        if self.transform != None:
            # apply image preprocessing
            image = self.transform(image)

        #captions_combined = []
        #max_len = 0  
        #for caption in caption_all_for_a_image:
        #    caption_str = str(caption).lower()
        #    tokens = nltk.tokenize.word_tokenize(caption_str)
        #    m = len(tokens) + 2 
        #    if m>max_len:
        #        max_len = m 
        #    caption = torch.Tensor([vocab(vocab.start_token())] +
        #                           [vocab(token) for token in tokens] +
        #                           [vocab(vocab.end_token())])
        #    captions_combined.append(caption) 
        #    #yield image, caption
        #return image,torch.Tensor(captions_combined)

        caption_str = str(caption_all_for_a_image).lower()
        tokens = nltk.tokenize.word_tokenize(caption_str)
        caption = torch.Tensor([vocab(vocab.start_token())] +
                                   [vocab(token) for token in tokens] +
                                   [vocab(vocab.end_token())])

        return image,caption

    def __len__(self):
        return len(self.all_imgs_path)

++++++++++++++++++++++++++++++++++++

最佳答案

首先,使用 str() 将字幕列表转换为单个字符串 (caption_str = str(caption_all_for_a_image)) 主意:

cap = ['a sentence', 'bla bla bla']
str(cap)

返回此:

"['a sentence', 'bla bla bla']"

请注意,['', ' 是结果字符串的一部分!

您可以随机选择一个标题:

import random
...
cap_idx = random.randi(0, len(caption_all_for_a_image)-1)  # pick one at random
caption_str = caption_all_for_a_image[cap_idx].lower()  # actual selection

关于python - 如何处理 PyTorch 中图像字幕目录中的多标签数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53442510/

相关文章:

python - 如何编写 PyTorch 顺序模型?

machine-learning - 在测试中使用增强数据图像

python - 如何在 Python 中对这个元组执行操作并转换为另一个元组?

python - 从坐标质心获取最近的 pandas df 坐标

pytorch - torchvision.models.resnet 和 torch.hub.load 有什么不同?

python - 运行时错误: NCCL Error 2: unhandled system error

python - OSError : Error no file named ['pytorch_model.bin' , 'tf_model.h5' , 'model.ckpt.index' ]

python - NumPy - 什么是广播?

python - 弹出元组列表中与元组邻居列表匹配的元组

python - 如何从Python中的本地文件获取特定XPath内的原始所有原始html