Я создаю класс с помощью этого кода
Код: Выделить всё
source_dir = r'./river-water-segmentation-dataset/riwa_v2'
subdir = os.listdir(source_dir)
filepaths = []
labels = []
for i in subdir:
classpath = os.path.join(source_dir, i)
if os.path.isdir(classpath):
file_list = os.listdir(classpath)
for f in file_list:
file_path = os.path.join(classpath, f)
filepaths.append(file_path)
labels.append(i)
paths = pd.Series(filepaths, name='paths')
labels = pd.Series(labels, name='labels')
df = pd.concat([paths, labels], axis=1)
print(df.head())
print("========================")
print(df['labels'].value_counts())
print("=========================")
print('Total data: ', len(df))
Код: Выделить всё
sample_list = []
max_size = 1500# TODO: change this value
grouping = df.groupby('labels')
for label in df['labels'].unique():
group = grouping.get_group(label)
group_size = len(group)
if group_size > max_size:
samples = group.sample(max_size, replace=False, weights=None, axis=0).reset_index(drop=True)
else:
samples = group.sample(frac=1.0, replace=False, axis=0).reset_index(drop=True)
sample_list.append(samples)
df = pd.concat(sample_list, axis=0).reset_index(drop=True)
print(df['labels'].value_counts())
print('Total data: ', len(df))
Код: Выделить всё
import os
import shutil
from tensorflow.keras.preprocessing.image import ImageDataGenerator
working_dir = r'./river-water-segmentation-dataset/riwa_v2/cropped'
aug_dir = os.path.join(working_dir, 'aug')
if os.path.isdir(aug_dir):
shutil.rmtree(aug_dir)
os.mkdir(aug_dir)
for label in df['labels'].unique():
dir_path=os.path.join(aug_dir, label)
os.mkdir(dir_path)
print(os.listdir(aug_dir))
target = 700 # set the target count for each class in df
gen = ImageDataGenerator(
rotation_range = 90,
horizontal_flip = True,
vertical_flip = True,
)
grouping = df.groupby('labels') # group by class
for label in df['labels'].unique(): # for every class
group = grouping.get_group(label) # a dataframe holding only rows with the specificied label
sample_count = len(group) # determine how many samples there are in this class
# if group.empty:
# print(f"No images found for label '{label}'. Skipping augmentation.")
# continue
if sample_count < target: # if the class has less than target number of images
aug_img_count = 0
delta = target - sample_count # number of augmented images to create
target_dir = os.path.join(aug_dir, label) # define where to write the images
aug_gen = gen.flow_from_dataframe(
group,
x_col = 'paths',
y_col = None,
target_size = (1420, 1080), # change this target size based on transfer learning model
class_mode = None,
batch_size = 1,
shuffle = False,
save_to_dir = target_dir,
save_prefix = 'aug-',
save_format='jpg'
)
images = next(aug_gen) # Try fetching a batch
print(f"Generated {len(images)} images.")
while aug_img_count < delta:
images = next(aug_gen)
aug_img_count += len(images)
Выполнял код более 10 минут. и в результате найдено 0 проверенных имен файлов изображений. Что-то я сделал не так? Это потому, что я загружаю версию tensorflow для процессора?
Редактировать 1: я действительно думал, что это из-за проблемы с размером, поэтому я обрезаю все изображения набора данных до одинакового размера, а код по-прежнему не работает. работа.
Подробнее здесь: https://stackoverflow.com/questions/792 ... -imagedata