croppie_coffee_ug / scripts /label_training_images.py
rgautroncgiar's picture
commiting to fix merge conflict
ce04c8c
import cv2
import matplotlib.pyplot as plt
from matplotlib.path import Path
plt.rcParams['figure.dpi'] = 100
from PIL import ImageColor
from pathlib import Path
import glob
import os
import json
def annotate_images_dataset(image_folder, label_folder, class_file_path, saving_folder, hex_class_colors=None, show=False):
"""
Allows to visualize a set of images and corresponding YOLO labels.
Args:
image_folder (str): path of the folder containing the images for object detection
label_folder (str): path of the folder containing the labels corresponding to the images for object detection
class_file_path (str): path of the json file containing the labels of the object classes
saving_folder (str): path of the folder
hex_class_colors (dict, optional): dictionary with HEX color for each label
show (bool, optional): if True, a prompt with the labelled image opens
"""
class_dic = get_class_dic(class_file_path)
Path(saving_folder).mkdir(parents=True, exist_ok=True)
if not hex_class_colors:
hex_class_colors = {class_name: (255, 0, 0) for class_name in class_dic.values()}
color_map = {key: ImageColor.getcolor(hex_class_colors[class_dic[key]], 'RGB') for key in [*class_dic]}
label_paths = sorted(glob.glob(os.path.join(label_folder, '*')))
n_labels = len(label_paths)
for i, label_path in enumerate(label_paths):
i += 1
if i % 100 == 0:
progress = i / n_labels
print(f'{progress: .0%} -> image {i} out of {n_labels}')
file_name = str(label_path).split('/')[-1].split('.')[0]
image_file = file_name + '.jpg'
image_path = os.path.join(image_folder, image_file)
if os.path.isfile(image_path):
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
dh, dw, _ = img.shape
with open(label_path, 'r') as f:
data = f.readlines()
for yolo_box in data:
yolo_box = yolo_box.strip()
c, x, y, w, h = map(float, yolo_box.split(' '))
l = int((x - w / 2) * dw)
r = int((x + w / 2) * dw)
t = int((y - h / 2) * dh)
b = int((y + h / 2) * dh)
if l < 0:
l = 0
if r > dw - 1:
r = dw - 1
if t < 0:
t = 0
if b > dh - 1:
b = dh - 1
cv2.rectangle(img, (l, t), (r, b), color_map[c], 3)
if show:
plt.imshow(img)
plt.show()
plt.imsave(os.path.join(saving_folder, f'annotated_{image_file}'), img)
else:
print(f'WARNING: {image_path} does not exists')
def get_class_dic(classe_file_path):
"""
Turns a label list txt file into a dict with numerical class as key and corresponding label as value
Args:
classe_file_path (str): path to the json file listing the labels
Returns:
dict: dictionary of numerical class as key and corresponding label as value
"""
class_dic = {}
with open(classe_file_path) as f:
class_dic = json.load(f)
class_dic = {int(k):v for k,v in class_dic.items()}
return class_dic
if __name__ == '__main__':
dataset_folder_names = ['train', 'val']
dataset_prefix_folder = '../data'
saving_prefix_folder = '../_labelled_dataset_images'
show = not True
hex_class_colors = {'green_cherry': '#9CF09A',
'yellow_cherry': '#F3C63D',
'red_cherry': '#F44336',
'dark_brown_cherry': '#C36105',
'low_visibility_unsure': '#02D5FA'}
for dataset_folder_name in dataset_folder_names:
print(f'dataset: {dataset_folder_name}:\n')
full_saving_folder = os.path.join(saving_prefix_folder, dataset_folder_name)
full_dataset_folder = os.path.join(dataset_prefix_folder, dataset_folder_name)
class_file_path = os.path.join('../', 'classes.json')
image_folder = os.path.join(full_dataset_folder, 'images')
label_folder = os.path.join(full_dataset_folder, 'labels')
annotate_images_dataset(
image_folder=image_folder,
label_folder=label_folder,
class_file_path=class_file_path,
saving_folder=full_saving_folder,
hex_class_colors=hex_class_colors,
show=show,
)