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