forked from bo-zhang-cs/CACNet-Pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKUPCP_dataset.py
144 lines (132 loc) · 5.92 KB
/
KUPCP_dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import os
import cv2
import numpy as np
import pickle
import lmdb
import datetime
import torch
import PIL.Image as Image
from torch.utils.data import DataLoader, Dataset
import torchvision.transforms as transforms
import json
import matplotlib.pyplot as plt
import math
from numpy import random
from config_classification import cfg
IMAGE_NET_MEAN = [0.485, 0.456, 0.406]
IMAGE_NET_STD = [0.229, 0.224, 0.225]
composition_cls = ['rule of thirds(RoT)', 'vertical', 'horizontal', 'diagonal', 'curved',
'triangle', 'center', 'symmetric', 'pattern']
class CompositionDataset(Dataset):
def __init__(self, split, keep_aspect_ratio):
self.split = split
self.keep_aspect = keep_aspect_ratio
data_root = cfg.KUPCP_dir
assert os.path.exists(data_root), data_root
if split == 'train':
self.image_dir = os.path.join(data_root, 'train_img')
self.label_txt = os.path.join(data_root, 'train_label.txt')
else:
self.image_dir = os.path.join(data_root, 'test_img')
self.label_txt = os.path.join(data_root, 'test_label.txt')
self.annotations = self.gather_annotation()
if self.split == 'train':
self.transformer = transforms.Compose([
transforms.Resize((cfg.image_size[0], cfg.image_size[1])),
transforms.ColorJitter(brightness=0.125, contrast=0.5, saturation=0.5, hue=0.05),
transforms.RandomHorizontalFlip(0.5),
transforms.ToTensor(),
transforms.Normalize(mean=IMAGE_NET_MEAN, std=IMAGE_NET_STD)
])
else:
self.transformer = transforms.Compose([
transforms.Resize((cfg.image_size[0], cfg.image_size[1])),
transforms.ToTensor(),
transforms.Normalize(mean=IMAGE_NET_MEAN, std=IMAGE_NET_STD)
])
def gather_annotation(self):
image_list = os.listdir(self.image_dir)
image_list = sorted(image_list, key=lambda k: float(os.path.splitext(k)[0]))
annotation = []
image_idx = 0
txt_idx = 0
with open(self.label_txt, 'r') as f:
for line in f.readlines():
txt_idx += 1
image_name = image_list[image_idx]
if txt_idx < int(os.path.splitext(image_name)[0]):
continue
image_idx += 1
assert int(os.path.splitext(image_name)[0]) == txt_idx, [txt_idx, image_name, line]
image_path = os.path.join(self.image_dir, image_name)
assert os.path.exists(image_path), image_path
labels = line.strip().split(' ')
labels = [int(l) for l in labels]
assert len(labels) == len(composition_cls), labels
categories = [i for i in range(len(labels)) if labels[i] == 1]
if len(categories) > 0:
if self.split == 'test':
annotation.append((image_name, categories))
else:
for c in categories:
annotation.append((image_name, [c]))
# annotation.append((image_name, categories))
# print(image_name, categories, [composition_cls[c] for c in categories])
# else:
# print(image_name, labels, categories)
print('{} set, total {} images'.format(
self.split, len(annotation)))
return annotation
def gather_training_annotation(self):
image_list = os.listdir(self.image_dir)
image_list = sorted(image_list, key=lambda k: float(os.path.splitext(k)[0]))
annotation = [[] for i in range(9)]
with open(self.label_txt, 'r') as f:
for image_name, line in zip(image_list, f.readlines()):
image_path = os.path.join(self.image_dir, image_name)
assert os.path.exists(image_path), image_path
labels = line.strip().split(' ')
labels = [int(l) for l in labels]
assert len(labels) == len(composition_cls), labels
categories = [i for i in range(len(labels)) if labels[i] == 1]
if len(categories) > 0:
for c in categories:
annotation[c].append(image_name)
for c in range(9):
print('{}, total {} training images'.format(
composition_cls[c], len(annotation[c])))
return annotation
def __len__(self):
return len(self.annotations)
def __getitem__(self, index):
image_name, cls = self.annotations[index]
if self.split == 'train' and len(cls) > 1:
# cls = [random.choice(cls)]
cls = [cls[-1]]
cls = torch.tensor(cls).long()
image_file = os.path.join(self.image_dir, image_name)
src = Image.open(image_file).convert('RGB')
width, height = src.size
im = self.transformer(src)
return im, cls, image_file
def check_jpg_file(path):
file_list = [file for file in os.listdir(path) if file.endswith('.jpg')]
for file in file_list:
image_file = os.path.join(path, file)
with open(image_file, 'rb') as f:
check_chars = f.read()[-2:]
if check_chars != b'\xff\xd9':
# print('Not complete image', image_file)
im = cv2.imread(image_file)
cv2.imwrite(image_file, im)
else:
im = cv2.imread(image_file)
if __name__ == '__main__':
# remove several wrong images
# check_jpg_file(os.path.join(cfg.KUPCP_path, 'train_img'))
# check_jpg_file(os.path.join(cfg.KUPCP_path, 'test_img'))
comp_dataset = CompositionDataset(split='train', keep_aspect_ratio=False)
dataloader = DataLoader(comp_dataset, batch_size=8, num_workers=0, shuffle=True)
for batch_idx, data in enumerate(dataloader):
im, cls, comp = data
print(im.shape, cls.shape, len(comp))