如何从目录处理多标签数据集以在PyTorch中进行图像字幕

时间:2018-11-23 07:43:22

标签: python pytorch

我需要PyTorch的帮助, 关于数据加载器和数据集 有人可以帮助/指导我

这是我的查询: 我正在尝试使用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”个字幕。

我能够创建一个自定义的Dataset类,因为将返回完整的字幕文件内容。但是我只希望返回一根单独的气体。

有关如何实现此目标的任何指导/建议。

++++++++++++++++++++++++++++++++++++++++++++++++ + 这是我设计的课程:

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)

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

1 个答案:

答案 0 :(得分:1)

首先,使用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