Skip to main content

rvlib/tools_data/
coco_io.rs

1use std::{
2    collections::HashMap,
3    fmt::{Debug, Display},
4    mem,
5    path::{Path, PathBuf},
6    thread::{self, JoinHandle},
7    vec,
8};
9
10use serde::{Deserialize, Serialize};
11use tracing::info;
12
13use crate::{
14    GeoFig,
15    cfg::ExportPath,
16    file_util::{self, PathPair, path_to_str},
17    image_util,
18    meta_data::MetaData,
19    result::trace_ok_warn,
20    tools_data::core::polygon_to_geofig,
21    util::version_label,
22};
23use rvimage_domain::{BbF, Canvas, ShapeI, TPtF};
24use rvimage_domain::{RvError, RvResult, rverr, to_rv};
25
26use super::{
27    BboxToolData, BrushToolData, InstanceAnnotate, InstanceExportData, Rot90ToolData,
28    annotations::InstanceAnnotations,
29    brush_data::BrushAnnoMap,
30    core::{CocoSegmentation, ExportAsCoco, new_random_colors},
31};
32
33#[derive(Serialize, Deserialize, Debug, Default)]
34struct CocoInfo {
35    description: String,
36}
37impl Display for CocoInfo {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.write_str(&self.description)
40    }
41}
42
43#[derive(Serialize, Deserialize, Debug)]
44struct CocoImage {
45    id: u32,
46    width: u32,
47    height: u32,
48    file_name: String,
49}
50
51#[derive(Serialize, Deserialize, Debug)]
52struct CocoBboxCategory {
53    id: u32,
54    name: String,
55}
56
57#[derive(Serialize, Deserialize, Debug)]
58struct CocoAnnotation {
59    id: u32,
60    image_id: u32,
61    category_id: u32,
62    bbox: [TPtF; 4],
63    segmentation: Option<CocoSegmentation>,
64    area: Option<TPtF>,
65}
66
67fn colors_to_string(colors: &[[u8; 3]]) -> Option<String> {
68    colors
69        .iter()
70        .map(|[r, g, b]| format!("{r};{g};{b}"))
71        .reduce(|s1, s2| format!("{s1}_{s2}"))
72}
73
74fn string_to_colors(s: &str) -> RvResult<Vec<[u8; 3]>> {
75    let make_err = || rverr!("cannot convert str {} to rgb", s);
76    s.trim()
77        .split('_')
78        .map(|rgb_str| {
79            let mut rgb = [0; 3];
80            let mut it = rgb_str.split(';');
81            for c in &mut rgb {
82                *c = it
83                    .next()
84                    .and_then(|s| s.parse().ok())
85                    .ok_or_else(make_err)?;
86            }
87            Ok(rgb)
88        })
89        .collect::<RvResult<Vec<[u8; 3]>>>()
90}
91
92fn get_n_rotations(rotation_data: Option<&Rot90ToolData>, file_path: &str) -> u8 {
93    rotation_data
94        .and_then(|d| d.get_annos(file_path))
95        .map_or(0, |n_rot| n_rot.to_num())
96}
97
98fn insert_elt<A>(
99    elt: A,
100    annos: &mut HashMap<String, (Vec<A>, Vec<usize>, ShapeI)>,
101    cat_idx: usize,
102    n_rotations: u8,
103    path_as_key: String,
104    shape_coco: ShapeI,
105) where
106    A: InstanceAnnotate,
107{
108    let geo = trace_ok_warn(elt.rot90_with_image_ntimes(shape_coco, n_rotations));
109    if let Some(geo) = geo {
110        if let Some(annos_of_image) = annos.get_mut(&path_as_key) {
111            annos_of_image.0.push(geo);
112            annos_of_image.1.push(cat_idx);
113        } else {
114            annos.insert(
115                path_as_key,
116                (
117                    vec![geo],
118                    vec![cat_idx],
119                    ShapeI::new(shape_coco.w, shape_coco.h),
120                ),
121            );
122        }
123    }
124}
125
126fn instance_to_coco_anno<A>(
127    inst_anno: &A,
128    shape_im_unrotated: ShapeI,
129    n_rotations: u8,
130    is_export_coords_absolute: bool,
131    file_path: &str,
132) -> RvResult<([f64; 4], Option<CocoSegmentation>)>
133where
134    A: InstanceAnnotate,
135{
136    // to store data corresponding to the image on the disk, we need to invert the
137    // applied rotations
138    let n_rots_inverted = (4 - n_rotations) % 4;
139    let shape_rotated = shape_im_unrotated.rot90_with_image_ntimes(n_rotations);
140    let inst_anno = inst_anno
141        .clone()
142        .rot90_with_image_ntimes(shape_rotated, n_rots_inverted)?;
143
144    let bb = inst_anno.enclosing_bb();
145
146    let segmentation = inst_anno.to_cocoseg(shape_im_unrotated, is_export_coords_absolute)?;
147    let (imw, imh) = if is_export_coords_absolute {
148        (1.0, 1.0)
149    } else {
150        (
151            TPtF::from(shape_im_unrotated.w),
152            TPtF::from(shape_im_unrotated.h),
153        )
154    };
155
156    let bb_f = [bb.x / imw, bb.y / imh, bb.w / imw, bb.h / imh];
157    if bb_f[1] * bb_f[2] < 1e-6 {
158        tracing::warn!("annotation in {file_path} has no area {bb:?}.");
159    }
160    Ok((bb_f, segmentation))
161}
162
163struct WarnerCounting<'a> {
164    n_warnings: usize,
165    n_max_warnings: usize,
166    suppressing: bool,
167    suppress_str: &'a str,
168}
169impl<'a> WarnerCounting<'a> {
170    fn new(n_max_warnings: usize, suppress_str: &'a str) -> Self {
171        Self {
172            n_warnings: 0,
173            n_max_warnings,
174            suppressing: false,
175            suppress_str,
176        }
177    }
178    fn warn_str<'b>(&mut self, msg: &'b str) -> Option<&'b str>
179    where
180        'a: 'b,
181    {
182        if self.n_warnings < self.n_max_warnings {
183            self.n_warnings += 1;
184            Some(msg)
185        } else if !self.suppressing {
186            self.suppressing = true;
187            Some(self.suppress_str)
188        } else {
189            None
190        }
191    }
192    fn warn(&mut self, msg: &str) {
193        if let Some(msg) = self.warn_str(msg) {
194            tracing::warn!(msg);
195        }
196    }
197}
198
199#[derive(Serialize, Deserialize, Debug, Default)]
200pub struct CocoExportData {
201    info: CocoInfo,
202    images: Vec<CocoImage>,
203    annotations: Vec<CocoAnnotation>,
204    categories: Vec<CocoBboxCategory>,
205}
206impl CocoExportData {
207    pub fn from_tools_data<T, A>(
208        tools_data: T,
209        rotation_data: Option<&Rot90ToolData>,
210        prj_path: Option<&Path>,
211        double_check_shape: bool,
212    ) -> Self
213    where
214        T: ExportAsCoco<A>,
215        A: InstanceAnnotate + 'static,
216    {
217        type AnnoValue<'a, A> = (&'a String, &'a (Vec<A>, Vec<usize>, ShapeI));
218
219        let (options, label_info, anno_map, coco_file) = tools_data.separate_data();
220        let color_str = if let Some(s) = colors_to_string(label_info.colors()) {
221            format!(", {s}")
222        } else {
223            String::new()
224        };
225        let info_str = format!(
226            "created with RV Image {}, https://github.com/bertiqwerty/rvimage{color_str}",
227            version_label()
228        );
229        let info = CocoInfo {
230            description: info_str,
231        };
232        let export_data =
233            InstanceExportData::from_tools_data(&options, label_info, coco_file, anno_map);
234
235        let make_image_map = |(idx, (file_path, (_, _, shape))): (usize, AnnoValue<A>)| CocoImage {
236            id: idx as u32,
237            width: shape.w,
238            height: shape.h,
239            file_name: file_path.clone(),
240        };
241        let images = export_data
242            .annotations
243            .iter()
244            .enumerate()
245            .map(make_image_map)
246            .collect::<Vec<_>>();
247
248        let categories = export_data
249            .labels
250            .iter()
251            .zip(export_data.cat_ids.iter())
252            .map(|(label, cat_id)| CocoBboxCategory {
253                id: *cat_id,
254                name: label.clone(),
255            })
256            .collect::<Vec<_>>();
257
258        let mut box_id = 0;
259        let mut imagesum_elapsed = 0;
260        let mut n_images_exported = 1;
261        let make_anno_map =
262            |(image_idx, (file_path, (bbs, cat_idxs, shape))): (usize, AnnoValue<A>)| {
263                let now = std::time::Instant::now();
264                let prj_path = if let Some(prj_path) = prj_path {
265                    prj_path
266                } else {
267                    Path::new("")
268                };
269                let p = PathPair::new(file_path.clone(), prj_path);
270                let p_abs = p.path_absolute();
271                let shape = if Path::new(p_abs).exists() && double_check_shape {
272                    let im = trace_ok_warn(image_util::read_image(file_path));
273                    if let Some(im) = im {
274                        ShapeI::new(im.width(), im.height())
275                    } else {
276                        *shape
277                    }
278                } else {
279                    *shape
280                };
281                let n_rotations = get_n_rotations(rotation_data, file_path);
282                let annos = bbs
283                    .iter()
284                    .zip(cat_idxs.iter())
285                    .filter_map(|(inst_anno, cat_idx): (&A, &usize)| {
286                        trace_ok_warn(instance_to_coco_anno(
287                            inst_anno,
288                            shape,
289                            n_rotations,
290                            options.is_export_absolute,
291                            file_path,
292                        ))
293                        .and_then(|(bb_f, segmentation)| {
294                            box_id += 1;
295                            let cat_id = export_data.cat_ids.get(*cat_idx);
296                            cat_id.map(|cat_id| CocoAnnotation {
297                                id: box_id - 1,
298                                image_id: image_idx as u32,
299                                category_id: *cat_id,
300                                bbox: bb_f,
301                                segmentation,
302                                area: Some(bb_f[2] * bb_f[3]),
303                            })
304                        })
305                    })
306                    .collect::<Vec<_>>();
307                let elapsed = now.elapsed();
308                imagesum_elapsed += elapsed.as_millis();
309                if imagesum_elapsed > 10000 && image_idx % n_images_exported == 0 {
310                    let ave = imagesum_elapsed as usize / (image_idx + 1);
311                    tracing::info!(
312                        "converting with {} ms/image, {}/{}, estimated time left: {} s",
313                        ave,
314                        image_idx + 1,
315                        export_data.annotations.len(),
316                        ave * (export_data.annotations.len() - image_idx - 1) / 1000
317                    );
318                    if n_images_exported == 1 {
319                        n_images_exported = image_idx;
320                        tracing::info!(
321                            "If your export is too slow, consider skipping the shape double check."
322                        )
323                    }
324                }
325                annos
326            };
327        let annotations = export_data
328            .annotations
329            .iter()
330            .enumerate()
331            .flat_map(make_anno_map)
332            .collect::<Vec<_>>();
333
334        CocoExportData {
335            info,
336            images,
337            annotations,
338            categories,
339        }
340    }
341
342    #[allow(clippy::too_many_lines)]
343    pub fn convert_to_toolsdata(
344        self,
345        coco_file: ExportPath,
346        rotation_data: Option<&Rot90ToolData>,
347    ) -> RvResult<(BboxToolData, BrushToolData)> {
348        let cat_ids: Vec<u32> = self.categories.iter().map(|coco_cat| coco_cat.id).collect();
349        let labels: Vec<String> = self
350            .categories
351            .into_iter()
352            .map(|coco_cat| coco_cat.name)
353            .collect();
354        let color_str = self.info.description.split(',').next_back();
355        let colors: Vec<[u8; 3]> = if let Some(s) = color_str {
356            string_to_colors(s).unwrap_or_else(|_| new_random_colors(labels.len()))
357        } else {
358            new_random_colors(labels.len())
359        };
360        let id_image_map = self
361            .images
362            .iter()
363            .map(|coco_image: &CocoImage| {
364                Ok((
365                    coco_image.id,
366                    (
367                        coco_image.file_name.as_str(),
368                        coco_image.width,
369                        coco_image.height,
370                    ),
371                ))
372            })
373            .collect::<RvResult<HashMap<u32, (&str, u32, u32)>>>()?;
374
375        let mut annotations_bbox: HashMap<String, (Vec<GeoFig>, Vec<usize>, ShapeI)> =
376            HashMap::new();
377        let mut annotations_brush: HashMap<String, (Vec<Canvas>, Vec<usize>, ShapeI)> =
378            HashMap::new();
379
380        let n_annotations = self.annotations.len();
381        let mut warner = WarnerCounting::new(
382            n_annotations / 10,
383            "suppressing further warnings during coco import",
384        );
385        for coco_anno in self.annotations {
386            if let Some((file_path, w_coco, h_coco)) = id_image_map.get(&coco_anno.image_id) {
387                // The annotations in the coco files created by RV Image are stored
388                // ignoring any orientation meta-data. Hence, if the image has been loaded
389                // and rotated with RV Image we correct the rotation.
390                let n_rotations = get_n_rotations(rotation_data, file_path);
391                let shape_coco = ShapeI::new(*w_coco, *h_coco);
392
393                let path_as_key = if file_path.starts_with("http") {
394                    file_util::url_encode(file_path)
395                } else {
396                    file_path.to_string()
397                };
398
399                let cat_idx = cat_ids
400                    .iter()
401                    .position(|cat_id| *cat_id == coco_anno.category_id)
402                    .ok_or_else(|| {
403                        rverr!(
404                            "could not find cat id {}, we only have {:?}",
405                            coco_anno.category_id,
406                            cat_ids
407                        )
408                    })?;
409                let coords_absolute = coco_anno.bbox.iter().any(|x| *x > 1.0);
410                let (w_factor, h_factor) = if coords_absolute {
411                    (1.0, 1.0)
412                } else {
413                    (f64::from(*w_coco), f64::from(*h_coco))
414                };
415                let bbox = [
416                    (w_factor * coco_anno.bbox[0]),
417                    (h_factor * coco_anno.bbox[1]),
418                    (w_factor * coco_anno.bbox[2]),
419                    (h_factor * coco_anno.bbox[3]),
420                ];
421
422                let mut insert_geo = |geo| {
423                    insert_elt(
424                        geo,
425                        &mut annotations_bbox,
426                        cat_idx,
427                        n_rotations,
428                        path_as_key.clone(),
429                        shape_coco,
430                    );
431                };
432
433                let bb = BbF::from(&bbox);
434
435                match coco_anno.segmentation {
436                    Some(CocoSegmentation::Polygon(poly)) => {
437                        let geofig = if poly.is_empty() {
438                            Ok(GeoFig::BB(bb))
439                        } else {
440                            polygon_to_geofig(&poly, w_factor, h_factor, bb, |s| warner.warn(s))
441                        };
442                        if let Ok(geofig) = geofig {
443                            insert_geo(geofig);
444                        } else {
445                            warner.warn(&format!("invalid segmentation in coco file {file_path}"));
446                        }
447                    }
448                    Some(CocoSegmentation::Rle(rle)) => {
449                        let canvas = rle.to_canvas(bb);
450                        if let Ok(canvas) = canvas {
451                            insert_elt(
452                                canvas,
453                                &mut annotations_brush,
454                                cat_idx,
455                                n_rotations,
456                                path_as_key,
457                                shape_coco,
458                            );
459                        } else {
460                            warner.warn(&format!("invalid segmentation in coco file {file_path}"));
461                        }
462                    }
463                    _ => {
464                        let geo = GeoFig::BB(bb);
465                        insert_geo(geo);
466                    }
467                }
468            }
469        }
470        let bbox_data = BboxToolData::from_coco_export_data(InstanceExportData {
471            labels: labels.clone(),
472            colors: colors.clone(),
473            cat_ids: cat_ids.clone(),
474            annotations: annotations_bbox,
475            coco_file: coco_file.clone(),
476            is_export_absolute: false,
477        })?;
478        let brush_data = BrushToolData::from_coco_export_data(InstanceExportData {
479            labels,
480            colors,
481            cat_ids,
482            annotations: annotations_brush,
483            coco_file,
484            is_export_absolute: false,
485        })?;
486        Ok((bbox_data, brush_data))
487    }
488}
489
490fn meta_data_to_coco_path(meta_data: &MetaData) -> RvResult<PathBuf> {
491    let export_folder = Path::new(
492        meta_data
493            .export_folder
494            .as_ref()
495            .ok_or_else(|| RvError::new("no export folder given"))?,
496    );
497    let opened_folder = meta_data
498        .opened_folder
499        .as_ref()
500        .map(PathPair::path_absolute)
501        .ok_or_else(|| RvError::new("no folder open"))?;
502    let parent = Path::new(opened_folder)
503        .parent()
504        .and_then(|p| p.file_stem())
505        .and_then(|p| p.to_str());
506
507    let opened_folder_name = Path::new(opened_folder)
508        .file_stem()
509        .and_then(|of| of.to_str())
510        .ok_or_else(|| rverr!("cannot find folder name  of {}", opened_folder))?;
511    let file_name = if let Some(p) = parent {
512        format!("{p}_{opened_folder_name}_coco.json")
513    } else {
514        format!("{opened_folder_name}_coco.json")
515    };
516    Ok(export_folder.join(file_name))
517}
518fn get_cocofilepath(meta_data: &MetaData, coco_file: &ExportPath) -> RvResult<PathBuf> {
519    if path_to_str(&coco_file.path)?.is_empty() {
520        meta_data_to_coco_path(meta_data)
521    } else {
522        Ok(coco_file.path.clone())
523    }
524}
525
526pub fn to_per_file_crowd(brush_annotations_map: &mut BrushAnnoMap) {
527    for (i, (filename, (annos, _))) in brush_annotations_map.iter_mut().enumerate() {
528        if i % 10 == 0 {
529            info!("export - image #{i} converting {filename} to per-image-crowd");
530        }
531        if let Some(max_catidx) = annos.cat_idxs().iter().max() {
532            let mut canvas_idxes_of_cats = vec![vec![]; max_catidx + 1];
533            for i in 0..(annos.elts().len()) {
534                if let Some(cat_idxs) = annos
535                    .cat_idxs()
536                    .get(i)
537                    .and_then(|idx| canvas_idxes_of_cats.get_mut(*idx))
538                {
539                    cat_idxs.push(i);
540                }
541            }
542            let mut merged_canvases = vec![None; max_catidx + 1];
543            for (cat_idx, canvas_idxes) in canvas_idxes_of_cats.iter().enumerate() {
544                let mut merged_canvas: Option<Canvas> = None;
545                for canvas_idx in canvas_idxes {
546                    let elt = &annos.elts().get(*canvas_idx);
547                    if let Some(elt) = elt {
548                        if let Some(merged_canvas) = &mut merged_canvas {
549                            *merged_canvas = mem::take(merged_canvas).merge(elt);
550                        } else {
551                            merged_canvas = Some((*elt).clone());
552                        }
553                    }
554                }
555                if let Some(mc) = merged_canvases.get_mut(cat_idx) {
556                    *mc = merged_canvas;
557                };
558            }
559            let mut cat_idxes = vec![];
560            let elts = merged_canvases
561                .into_iter()
562                .enumerate()
563                .filter_map(|(i, cvs)| cvs.map(|cvs| (i, cvs)))
564                .map(|(i, cvs)| {
565                    cat_idxes.push(i);
566                    cvs
567                })
568                .collect();
569            let n_elts = cat_idxes.len();
570            let new_annos = trace_ok_warn(InstanceAnnotations::<Canvas>::new(
571                elts,
572                cat_idxes,
573                vec![false; n_elts],
574            ));
575            if let Some(new_annos) = new_annos {
576                *annos = new_annos;
577            }
578        }
579    }
580}
581
582/// Serialize annotations in Coco format. Any orientations changes applied with the rotation tool
583/// are reverted, since the rotation tool does not change the image file. Hence, the Coco file contains the annotation
584/// relative to the image as it is found in memory ignoring any meta-data.
585///
586/// # Errors
587/// - outpath name cannot be created due to weird characters or the like
588/// - serde write-to-json fails
589pub fn write_coco<T, A>(
590    meta_data: &MetaData,
591    tools_data: T,
592    rotation_data: Option<&Rot90ToolData>,
593    coco_file: &ExportPath,
594    double_check_shape: bool,
595) -> RvResult<(PathBuf, JoinHandle<RvResult<()>>)>
596where
597    T: ExportAsCoco<A> + Send + 'static,
598    A: InstanceAnnotate + 'static,
599{
600    let meta_data = meta_data.clone();
601    let coco_out_path = get_cocofilepath(&meta_data, coco_file)?;
602    let coco_out_path_for_thr = coco_out_path.clone();
603    let rotation_data = rotation_data.cloned();
604    let conn = coco_file.conn.clone();
605    let handle = thread::spawn(move || {
606        let coco_data = CocoExportData::from_tools_data(
607            tools_data,
608            rotation_data.as_ref(),
609            meta_data.prj_path(),
610            double_check_shape,
611        );
612        let data_str = serde_json::to_string(&coco_data)
613            .map_err(to_rv)
614            .inspect_err(|e| tracing::error!("export failed due to {e:?}"))?;
615
616        conn.write(
617            &data_str,
618            &coco_out_path_for_thr,
619            meta_data.ssh_cfg.as_ref(),
620        )
621        .inspect_err(|e| tracing::error!("export failed due to {e:?}"))?;
622        tracing::info!("exported coco labels to {coco_out_path_for_thr:?}");
623        Ok(())
624    });
625    Ok((coco_out_path, handle))
626}
627
628/// Import annotations in Coco format. Any orientations changes applied with the rotation tool
629/// to images that have annotations in the Coco file are applied to the annotations before importing. We expect, that
630/// the Coco file contains the annotations relative to the image as it is found in memory ignoring any meta-data.
631///
632/// # Errors
633/// - not a coco file
634/// - ssh connection problems
635pub fn read_coco(
636    meta_data: &MetaData,
637    coco_file: &ExportPath,
638    rotation_data: Option<&Rot90ToolData>,
639) -> RvResult<(BboxToolData, BrushToolData)> {
640    let coco_inpath = get_cocofilepath(meta_data, coco_file)?;
641    let coco_str = coco_file
642        .conn
643        .read(&coco_inpath, meta_data.ssh_cfg.as_ref())?;
644    let read_data: CocoExportData = serde_json::from_str(coco_str.as_str()).map_err(to_rv)?;
645    read_data.convert_to_toolsdata(coco_file.clone(), rotation_data)
646}
647
648#[cfg(test)]
649use {
650    super::core::CocoRle,
651    crate::{
652        cfg::{ExportPathConnection, SshCfg},
653        defer_file_removal,
654        meta_data::{ConnectionData, MetaDataFlags},
655        tracing_setup::init_tracing_for_tests,
656    },
657    file_util::DEFAULT_TMPDIR,
658    rvimage_domain::{BbI, make_test_bbs},
659    std::{fs, str::FromStr},
660};
661#[cfg(test)]
662fn make_meta_data(opened_folder: Option<&Path>) -> (MetaData, PathBuf) {
663    let opened_folder = if let Some(of) = opened_folder {
664        PathPair::new(of.to_str().unwrap().to_string(), Path::new(""))
665    } else {
666        PathPair::new("xi".to_string(), Path::new(""))
667    };
668    let test_export_folder = DEFAULT_TMPDIR.clone();
669
670    if !test_export_folder.exists() {
671        match fs::create_dir(&test_export_folder) {
672            Ok(_) => (),
673            Err(e) => {
674                println!("{e:?}");
675            }
676        }
677    }
678
679    let test_export_path = DEFAULT_TMPDIR.join(format!("{}.json", opened_folder.path_absolute()));
680    let mut meta = MetaData::from_filepath(
681        test_export_path
682            .with_extension("egal")
683            .to_str()
684            .unwrap()
685            .to_string(),
686        0,
687        Path::new("egal"),
688    );
689    meta.opened_folder = Some(opened_folder);
690    meta.export_folder = Some(test_export_folder.to_str().unwrap().to_string());
691    meta.connection_data = ConnectionData::Ssh(SshCfg::default());
692    (meta, test_export_path)
693}
694#[cfg(test)]
695fn make_data_brush(
696    image_file: &Path,
697    opened_folder: Option<&Path>,
698    export_absolute: bool,
699    n_boxes: Option<usize>,
700) -> (BrushToolData, MetaData, PathBuf, ShapeI) {
701    use super::InstanceLabelDisplay;
702
703    let shape = ShapeI::new(100, 40);
704    let mut bbox_data = BrushToolData::default();
705    bbox_data.options.core.is_export_absolute = export_absolute;
706    bbox_data.coco_file = ExportPath::default();
707    bbox_data
708        .label_info
709        .push("x".to_string(), None, None)
710        .unwrap();
711
712    bbox_data
713        .label_info
714        .remove_catidx(0, &mut bbox_data.annotations_map);
715
716    let mut bbs = make_test_bbs();
717    bbs.extend(bbs.clone());
718    bbs.extend(bbs.clone());
719    bbs.extend(bbs.clone());
720    bbs.extend(bbs.clone());
721    bbs.extend(bbs.clone());
722    bbs.extend(bbs.clone());
723    bbs.extend(bbs.clone());
724    if let Some(n) = n_boxes {
725        bbs = bbs[0..n].to_vec();
726    }
727
728    let annos = bbox_data.get_annos_mut(image_file.as_os_str().to_str().unwrap(), shape);
729    if let Some(a) = annos {
730        for bb in bbs {
731            let mut mask = vec![0; (bb.w * bb.h) as usize];
732            mask[4] = 1;
733            let c = Canvas {
734                bb: bb.into(),
735                mask,
736                intensity: 0.5,
737            };
738            a.add_elt(c, 0, InstanceLabelDisplay::None);
739        }
740    }
741
742    let (meta, test_export_path) = make_meta_data(opened_folder);
743    (bbox_data, meta, test_export_path, shape)
744}
745#[cfg(test)]
746pub fn make_data_bbox(
747    image_file: &Path,
748    opened_folder: Option<&Path>,
749    export_absolute: bool,
750    n_boxes: Option<usize>,
751) -> (BboxToolData, MetaData, PathBuf, ShapeI) {
752    let shape = ShapeI::new(20, 10);
753    let mut bbox_data = BboxToolData::new();
754    bbox_data.options.core.is_export_absolute = export_absolute;
755    bbox_data.coco_file = ExportPath::default();
756    bbox_data
757        .label_info
758        .push("x".to_string(), None, None)
759        .unwrap();
760
761    bbox_data
762        .label_info
763        .remove_catidx(0, &mut bbox_data.annotations_map);
764
765    let mut bbs = make_test_bbs();
766    bbs.extend(bbs.clone());
767    bbs.extend(bbs.clone());
768    bbs.extend(bbs.clone());
769    bbs.extend(bbs.clone());
770    bbs.extend(bbs.clone());
771    bbs.extend(bbs.clone());
772    bbs.extend(bbs.clone());
773    if let Some(n) = n_boxes {
774        bbs = bbs[0..n].to_vec();
775    }
776
777    let annos = bbox_data.get_annos_mut(image_file.as_os_str().to_str().unwrap(), shape);
778    if let Some(a) = annos {
779        for bb in bbs {
780            a.add_bb(bb, 0, super::InstanceLabelDisplay::IndexLr);
781        }
782    }
783    let (meta, test_export_path) = make_meta_data(opened_folder);
784    (bbox_data, meta, test_export_path, shape)
785}
786
787#[cfg(test)]
788fn is_image_duplicate_free(coco_data: &CocoExportData) -> bool {
789    let mut image_ids = coco_data.images.iter().map(|i| i.id).collect::<Vec<_>>();
790    image_ids.sort();
791    let len_prev = image_ids.len();
792    image_ids.dedup();
793    image_ids.len() == len_prev
794}
795
796#[cfg(test)]
797fn no_image_dups<P>(coco_file: P)
798where
799    P: AsRef<Path> + Debug,
800{
801    let s = file_util::read_to_string(&coco_file).unwrap();
802    let read_raw: CocoExportData = serde_json::from_str(s.as_str()).unwrap();
803
804    assert!(is_image_duplicate_free(&read_raw));
805}
806#[test]
807fn test_coco_export() {
808    fn assert_coco_eq<T, A>(data: T, read: T, coco_file: &PathBuf)
809    where
810        T: ExportAsCoco<A> + Send + 'static,
811        A: InstanceAnnotate + 'static + Debug,
812    {
813        assert_eq!(data.label_info().cat_ids(), read.label_info().cat_ids());
814        assert_eq!(data.label_info().labels(), read.label_info().labels());
815        for (brush_anno, read_anno) in data.anno_iter().zip(read.anno_iter()) {
816            let (name, (instance_annos, shape)) = brush_anno;
817            let (read_name, (read_instance_annos, read_shape)) = read_anno;
818            assert_eq!(instance_annos.cat_idxs(), read_instance_annos.cat_idxs());
819            assert_eq!(
820                instance_annos.elts().len(),
821                read_instance_annos.elts().len()
822            );
823            for (i, (a, b)) in instance_annos
824                .elts()
825                .iter()
826                .zip(read_instance_annos.elts().iter())
827                .enumerate()
828            {
829                assert_eq!(a, b, "annos at index {} differ", i);
830            }
831            assert_eq!(name, read_name);
832            assert_eq!(shape, read_shape);
833        }
834        no_image_dups(coco_file);
835    }
836    fn write_read<T, A>(meta: &MetaData, tools_data: T) -> ((BboxToolData, BrushToolData), PathBuf)
837    where
838        T: ExportAsCoco<A> + Send + 'static,
839        A: InstanceAnnotate + 'static,
840    {
841        let coco_file = tools_data.cocofile_conn();
842        let (coco_file, handle) = write_coco(meta, tools_data, None, &coco_file, true).unwrap();
843        handle.join().unwrap().unwrap();
844        (
845            read_coco(
846                meta,
847                &ExportPath {
848                    path: coco_file.clone(),
849                    conn: ExportPathConnection::Local,
850                },
851                None,
852            )
853            .unwrap(),
854            coco_file,
855        )
856    }
857    fn test_br(file_path: &Path, opened_folder: Option<&Path>, export_absolute: bool) {
858        let (brush_data, meta, _, _) =
859            make_data_brush(file_path, opened_folder, export_absolute, None);
860        let ((_, read), coco_file) = write_read(&meta, brush_data.clone());
861        defer_file_removal!(&coco_file);
862        assert_coco_eq(brush_data, read, &coco_file);
863    }
864    fn test_bb(file_path: &Path, opened_folder: Option<&Path>, export_absolute: bool) {
865        let (bbox_data, meta, _, _) =
866            make_data_bbox(file_path, opened_folder, export_absolute, None);
867        let ((read, _), coco_file) = write_read(&meta, bbox_data.clone());
868        defer_file_removal!(&coco_file);
869        assert_coco_eq(bbox_data, read, &coco_file);
870    }
871    let tmpdir = &DEFAULT_TMPDIR;
872    let file_path = tmpdir.join("test_image.png");
873    test_br(&file_path, None, true);
874    test_bb(&file_path, None, true);
875    let folder = Path::new("http://localhost:8000/some_path");
876    let file = Path::new("http://localhost:8000/some_path/xyz.png");
877    test_br(file, Some(folder), false);
878    test_bb(file, Some(folder), false);
879}
880
881#[cfg(test)]
882const TEST_DATA_FOLDER: &str = "resources/test_data/";
883
884#[test]
885fn test_coco_import_export() {
886    let meta = MetaData::new(
887        None,
888        None,
889        ConnectionData::None,
890        None,
891        Some(PathPair::new("ohm_somefolder".to_string(), Path::new(""))),
892        Some(TEST_DATA_FOLDER.to_string()),
893        MetaDataFlags::default(),
894        None,
895    );
896    let test_file_src = format!("{TEST_DATA_FOLDER}catids_12_coco_imwolab.json");
897    let test_file = "tmp_coco.json";
898    defer_file_removal!(&test_file);
899    fs::copy(test_file_src, test_file).unwrap();
900    let export_path = ExportPath {
901        path: PathBuf::from_str(test_file).unwrap(),
902        conn: ExportPathConnection::Local,
903    };
904
905    let (read, _) = read_coco(&meta, &export_path, None).unwrap();
906    let (_, handle) = write_coco(&meta, read.clone(), None, &export_path.clone(), true).unwrap();
907    handle.join().unwrap().unwrap();
908    no_image_dups(&read.coco_file.path);
909    let (read, _) = read_coco(&meta, &export_path, None).unwrap();
910    for anno in read.anno_iter() {
911        let (_, (annos, _)) = anno;
912        for a in annos.elts() {
913            println!("{a:?}");
914            assert!(a.enclosing_bb().w * a.enclosing_bb().h > 1e-3);
915        }
916    }
917}
918
919#[test]
920fn test_coco_import() -> RvResult<()> {
921    init_tracing_for_tests();
922    fn test(filename: &str, cat_ids: Vec<u32>, reference_bbs: &[(BbI, &str)]) {
923        tracing::debug!(filename);
924        let meta = MetaData::new(
925            None,
926            None,
927            ConnectionData::None,
928            None,
929            Some(PathPair::new(filename.to_string(), Path::new(""))),
930            Some(TEST_DATA_FOLDER.to_string()),
931            MetaDataFlags::default(),
932            None,
933        );
934        tracing::debug!("{meta:?}");
935        let (read, _) = read_coco(&meta, &ExportPath::default(), None).unwrap();
936        assert_eq!(read.label_info.cat_ids(), &cat_ids);
937        assert_eq!(
938            read.label_info.labels(),
939            &vec!["first label", "second label"]
940        );
941        for (bb, file_path) in reference_bbs {
942            let annos = read.get_annos(file_path);
943            println!();
944            println!("{file_path:?}");
945            println!("{annos:?}");
946            assert!(annos.unwrap().elts().contains(&GeoFig::BB((*bb).into())));
947        }
948    }
949
950    let bb_im_ref_abs1 = [
951        (
952            BbI::from_arr(&[1, 1, 5, 5]),
953            "http://localhost:5000/%2Bnowhere.png",
954        ),
955        (
956            BbI::from_arr(&[11, 11, 4, 7]),
957            "http://localhost:5000/%2Bnowhere.png",
958        ),
959        (
960            BbI::from_arr(&[1, 1, 5, 5]),
961            "http://localhost:5000/%2Bnowhere2.png",
962        ),
963    ];
964    let bb_im_ref_abs2 = [
965        (BbI::from_arr(&[1, 1, 5, 5]), "nowhere.png"),
966        (BbI::from_arr(&[11, 11, 4, 7]), "nowhere.png"),
967        (BbI::from_arr(&[1, 1, 5, 5]), "nowhere2.png"),
968    ];
969    let bb_im_ref_relative = [
970        (BbI::from_arr(&[10, 100, 50, 500]), "nowhere.png"),
971        (BbI::from_arr(&[91, 870, 15, 150]), "nowhere.png"),
972        (BbI::from_arr(&[10, 1, 50, 5]), "nowhere2.png"),
973    ];
974    test("catids_12", vec![1, 2], &bb_im_ref_abs1);
975    test("catids_01", vec![0, 1], &bb_im_ref_abs2);
976    test("catids_12_relative", vec![1, 2], &bb_im_ref_relative);
977    Ok(())
978}
979
980#[test]
981fn color_vs_str() {
982    let colors = vec![[0, 0, 7], [4, 0, 101], [210, 9, 0]];
983    let s = colors_to_string(&colors);
984    let colors_back = string_to_colors(&s.unwrap()).unwrap();
985    assert_eq!(colors, colors_back);
986}
987
988#[test]
989fn test_rotation_export_import() {
990    fn test<T, A>(
991        coco_file: &PathBuf,
992        bbox_specifics: T,
993        meta_data: MetaData,
994        shape: ShapeI,
995        read_f: impl Fn(&MetaData, &ExportPath, Option<&Rot90ToolData>) -> T,
996    ) where
997        T: ExportAsCoco<A> + Send + 'static + Clone,
998        A: InstanceAnnotate + 'static + Debug,
999    {
1000        defer_file_removal!(&coco_file);
1001        let mut rotation_data = Rot90ToolData::default();
1002        let annos = rotation_data.get_annos_mut("some_path.png", shape);
1003        if let Some(annos) = annos {
1004            *annos = annos.increase();
1005        }
1006        let coco_file = bbox_specifics.cocofile_conn();
1007        let (out_path, handle) = write_coco(
1008            &meta_data,
1009            bbox_specifics.clone(),
1010            Some(&rotation_data),
1011            &coco_file,
1012            true,
1013        )
1014        .unwrap();
1015        handle.join().unwrap().unwrap();
1016        println!("write to {out_path:?}");
1017        let out_path = ExportPath {
1018            path: out_path,
1019            conn: ExportPathConnection::Local,
1020        };
1021        let read = read_f(&meta_data, &out_path, Some(&rotation_data));
1022
1023        for ((_, (anno_res, _)), (_, (anno_ref, _))) in
1024            bbox_specifics.anno_iter().zip(read.anno_iter())
1025        {
1026            for (read_elt, ref_elt) in anno_res.elts().iter().zip(anno_ref.elts().iter()) {
1027                assert_eq!(read_elt, ref_elt);
1028            }
1029        }
1030    }
1031    let (brush_specifics, meta_data, coco_file, shape) = make_data_brush(
1032        Path::new("some_path.png"),
1033        Some(Path::new("afolder")),
1034        false,
1035        None,
1036    );
1037    test(&coco_file, brush_specifics, meta_data, shape, |m, d, r| {
1038        read_coco(m, d, r).unwrap().1
1039    });
1040    let (bbox_specifics, meta_data, coco_file, shape) = make_data_bbox(
1041        Path::new("some_path.png"),
1042        Some(Path::new("afolder")),
1043        false,
1044        None,
1045    );
1046    test(&coco_file, bbox_specifics, meta_data, shape, |m, d, r| {
1047        read_coco(m, d, r).unwrap().0
1048    });
1049}
1050
1051#[test]
1052fn test_serialize_rle() {
1053    let rle = CocoRle {
1054        counts: vec![1, 2, 3, 4],
1055        size: (5, 6),
1056        intensity: None,
1057    };
1058    let rle = CocoSegmentation::Rle(rle);
1059    let s = serde_json::to_string(&rle).unwrap();
1060    println!("{s}");
1061    let rle2: CocoSegmentation = serde_json::from_str(&s).unwrap();
1062    assert_eq!(format!("{rle:?}"), format!("{rle2:?}"));
1063    let poly = CocoSegmentation::Polygon(vec![vec![1.0, 2.0]]);
1064    let s = serde_json::to_string(&poly).unwrap();
1065    println!("{s}");
1066    let poly2: CocoSegmentation = serde_json::from_str(&s).unwrap();
1067    assert_eq!(format!("{poly:?}"), format!("{poly2:?}"));
1068}
1069
1070#[test]
1071fn test_instance_to_coco() {
1072    let shape = ShapeI::new(2000, 2667);
1073    let bb = BbI::from_arr(&[1342, 1993, 8, 8]);
1074    let n_rot = 1;
1075    let canvas = Canvas {
1076        mask: vec![0; 64],
1077        bb,
1078        intensity: 0.5,
1079    };
1080    let coco_anno = instance_to_coco_anno(&canvas, shape, n_rot, false, "");
1081    assert!(coco_anno.is_err());
1082
1083    let shape_im = ShapeI::new(20, 40);
1084    let mut mask = vec![0; 4];
1085    mask[2] = 1;
1086    let canvas = Canvas {
1087        bb: BbI::from_arr(&[1, 1, 2, 2]),
1088        mask: mask.clone(),
1089        intensity: 0.5,
1090    };
1091    let n_rotations = 1;
1092
1093    let (_, segmentation) =
1094        instance_to_coco_anno(&canvas, shape_im, n_rotations, false, "").unwrap();
1095
1096    let coco_seg = canvas
1097        .rot90_with_image_ntimes(
1098            shape_im.rot90_with_image_ntimes(n_rotations),
1099            4 - n_rotations,
1100        )
1101        .unwrap()
1102        .to_cocoseg(shape_im, false)
1103        .unwrap();
1104    assert_ne!(coco_seg, None);
1105    assert_eq!(segmentation, coco_seg);
1106    let geo = GeoFig::BB(BbF::from_arr(&[1.0, 1.0, 2.0, 8.0]));
1107
1108    let n_rotations = 1;
1109
1110    let (bb_rot, segmentation) =
1111        instance_to_coco_anno(&geo, shape_im, n_rotations, true, "").unwrap();
1112    println!("{bb_rot:?}");
1113    let coco_seg = geo
1114        .rot90_with_image_ntimes(
1115            shape_im.rot90_with_image_ntimes(n_rotations),
1116            4 - n_rotations,
1117        )
1118        .unwrap()
1119        .to_cocoseg(shape_im, true)
1120        .unwrap();
1121    assert_ne!(coco_seg, None);
1122    assert_eq!(segmentation, coco_seg);
1123}
1124
1125#[test]
1126fn test_warner() {
1127    let suppress_msg = "no further warnings";
1128    let mut warner = WarnerCounting::new(3, suppress_msg);
1129    assert_eq!(warner.warn_str("a"), Some("a"));
1130    assert_eq!(warner.warn_str("a"), Some("a"));
1131    assert_eq!(warner.warn_str("b"), Some("b"));
1132    assert_eq!(warner.warn_str("a"), Some(suppress_msg));
1133    assert_eq!(warner.warn_str("a"), None);
1134}