Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow string as label in bbox lens #428

Merged
merged 3 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/hooks/useColorTransferFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,23 @@ export const createColorTransferFunction = (
}

if (dtype.kind === 'Category' && !continuousCategories) {
return createCategoricalTransferFunction(_.uniq(data), dtype);
return createCategoricalTransferFunction(
Object.values(dtype.categories),
dtype
);
}

if (dtype.kind === 'Category' && continuousCategories) {
const stats = makeStats(dtype, Object.values(dtype.categories));
return createContinuousTransferFunction(
(robust ? stats?.p5 : stats?.min) ?? 0,
(robust ? stats?.p95 : stats?.max) ?? 1,
dtype,
classBreaks
);
}

if (['int', 'float', 'Category'].includes(dtype.kind)) {
if (['int', 'float'].includes(dtype.kind)) {
const stats = makeStats(dtype, data);
return createContinuousTransferFunction(
(robust ? stats?.p5 : stats?.min) ?? 0,
Expand Down
34 changes: 22 additions & 12 deletions src/lenses/BoundingBoxLens/BBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,28 @@ const BBox = ({ x, y, width, height, color, label }: BBoxProps) => {
stroke={colorCss}
strokeWidth={2}
></rect>
<rect
x={x}
y={y - 11}
width={width}
height={12}
fill={colorCss}
stroke={colorCss}
strokeWidth={2}
></rect>
<text x={x} y={y} fontSize={12} fontWeight="bold" fill={textColorCss}>
{label}
</text>
{label && (
<>
<rect
x={x}
y={y - 11}
width={width}
height={12}
fill={colorCss}
stroke={colorCss}
strokeWidth={2}
></rect>
<text
x={x}
y={y}
fontSize={12}
fontWeight="bold"
fill={textColorCss}
>
{label}
</text>
</>
)}
</g>
);
};
Expand Down
218 changes: 126 additions & 92 deletions src/lenses/BoundingBoxLens/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
import { useColorTransferFunction } from '../../hooks';
import { useRef, useCallback, useState, useMemo } from 'react';
import { Lens } from '../../types';
import { DataColumn, Lens } from '../../types';
import 'twin.macro';
import { CategoricalDataType } from '../../datatypes';
import BBox from './BBox';
import useResizeObserver from '@react-hook/resize-observer';
import chroma from 'chroma-js';
import _ from 'lodash';
import { useColorTransferFunction } from '../../hooks';
import { useDataformat } from '../../dataformat';
import { NO_DATA as NO_DATA_COLOR } from '../../palettes';

type BBox = [number, number, number, number];
interface Label {
text: string;
color: chroma.Color;
}

const NO_VALUES: unknown[] = [];

function useLabels(column: DataColumn, value: unknown): Label[] {
const colorFunc = useColorTransferFunction(NO_VALUES, column.type);
const formatter = useDataformat();

return useMemo(() => {
if (column.type.kind === 'Sequence') {
const innerType = column.type.dtype;
const values = value as unknown[];
return values.map((x) => ({
text: formatter.format(x, innerType),
color: colorFunc(x),
}));
} else {
return [
{
text: formatter.format(value, column.type),
color: colorFunc(value),
},
];
}
}, [column, value, formatter, colorFunc]);
}

const BoundingBoxLens: Lens = ({ urls, values, columns }) => {
const container = useRef<HTMLDivElement>(null);
Expand All @@ -13,41 +47,30 @@ const BoundingBoxLens: Lens = ({ urls, values, columns }) => {
const [imgSize, setImgSize] = useState({ width: 0, height: 0 });
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });

// In case of single bounding box with label
const bboxColumnIndex = columns.findIndex((col) => col.type.kind === 'BoundingBox');
const categoryColumnIndex = columns.findIndex(
(col) => col.type.kind === 'Category'
);

// In case of multiple bounding boxes per image
const bboxesColumnIndex = columns.findIndex(
(col) => col.type.kind === 'Sequence' && col.type.dtype.kind === 'BoundingBox'
);
const categoriesColumnIndex = columns.findIndex(
(col) => col.type.kind === 'Sequence' && col.type.dtype.kind === 'Category'
);
const imageColumnIndex = columns.findIndex((col) => col.type.kind === 'Image');
const url = urls[imageColumnIndex];

const boxes = useMemo(() => {
if (bboxColumnIndex != -1) {
return [values[bboxColumnIndex] as number[]];
} else if (bboxesColumnIndex != -1) {
return values[bboxesColumnIndex] as [number[]];
} else {
return [];
}
}, [values, bboxColumnIndex, bboxesColumnIndex]);

const categories = useMemo(() => {
if (categoryColumnIndex != -1) {
return [values[categoryColumnIndex] as number];
} else if (categoriesColumnIndex != -1) {
return values[categoriesColumnIndex] as [number];
} else {
return [];
}
}, [values, categoryColumnIndex, categoriesColumnIndex]);
const bboxColumnIndex = columns.findIndex(
(col) =>
col.type.kind === 'BoundingBox' ||
(col.type.kind === 'Sequence' && col.type.dtype.kind === 'BoundingBox')
);
const boxes: BBox[] = useMemo(() => {
const boxValue = values[bboxColumnIndex] as number[] | number[][] | null;
if (!boxValue) return [];
return (
boxValue.length && !_.isArray(boxValue[0]) ? [boxValue] : boxValue
) as BBox[];
}, [values, bboxColumnIndex]);

const labelsColumnIndex = columns.findIndex(
(col) =>
col.type.kind === 'Category' ||
col.type.kind === 'str' ||
(col.type.kind === 'Sequence' &&
(col.type.dtype.kind === 'Category' || col.type.dtype.kind === 'str'))
);
const labels = useLabels(columns[labelsColumnIndex], values[labelsColumnIndex]);

// Natural dimensions of the image
const naturalWidth = imgSize.width;
Expand All @@ -72,19 +95,6 @@ const BoundingBoxLens: Lens = ({ urls, values, columns }) => {
const offsetWidth = (parentWidth - renderedWidth) / 2;
const offsetHeight = (parentHeight - renderedHeight) / 2;

const categoricalColumn =
columns[categoryColumnIndex] ?? columns[categoriesColumnIndex];
const categoricalDtype = (
categoricalColumn?.type?.kind === 'Sequence'
? categoricalColumn?.type?.dtype
: categoricalColumn?.type
) as CategoricalDataType | undefined;

const colorTransferFunction = useColorTransferFunction(
categories,
categoricalDtype
);

useResizeObserver(container, () => {
setContainerSize({
width: container.current?.offsetWidth ?? 0,
Expand Down Expand Up @@ -117,11 +127,8 @@ const BoundingBoxLens: Lens = ({ urls, values, columns }) => {
height={(box[3] - box[1]) * renderedHeight}
x={box[0] * renderedWidth + offsetWidth}
y={box[1] * renderedHeight + offsetHeight}
color={colorTransferFunction(categories[index])}
label={
categoricalDtype?.invertedCategories[categories[index]] ??
''
}
color={labels[index]?.color ?? NO_DATA_COLOR}
label={labels[index]?.text ?? ''}
/>
))}
</svg>
Expand All @@ -130,59 +137,86 @@ const BoundingBoxLens: Lens = ({ urls, values, columns }) => {
};

BoundingBoxLens.key = 'BoundingBoxView';
BoundingBoxLens.dataTypes = ['Image', 'BoundingBox', 'Sequence', 'Category'];
BoundingBoxLens.dataTypes = ['Image', 'BoundingBox', 'Sequence', 'Category', 'str'];
BoundingBoxLens.multi = true;
BoundingBoxLens.displayName = 'BoundingBox';
BoundingBoxLens.defaultHeight = 256;
BoundingBoxLens.filterAllowedColumns = (allColumns, selectedColumns) => {
if (selectedColumns.length === 3) return [];
const allowedColumns: DataColumn[] = [];

// allow exactly one image column
if (!selectedColumns.find(({ type }) => type.kind === 'Image')) {
allowedColumns.push(...allColumns.filter(({ type }) => type.kind === 'Image'));
}

const selectedTypes = selectedColumns.map((selectedCol) => selectedCol.type);
if (selectedColumns.length === 0)
return allColumns.filter(({ type }) =>
BoundingBoxLens.dataTypes.includes(type.kind)
);
const allowSequences = !selectedColumns.find(
({ type }) => type.kind !== 'Image' && type.kind !== 'Sequence'
);
const allowNonSequences = !selectedColumns.find(
({ type }) => type.kind === 'Sequence'
);

if (selectedTypes.find((type) => type.kind === 'Sequence')) {
return allColumns.filter(({ type }) => {
return type.kind === 'Sequence' || type.kind === 'Image';
});
} else if (
selectedTypes.find((type) => ['BoundingBox', 'Category'].includes(type.kind))
) {
return allColumns.filter(({ type }) => {
return (
// allow exactly one bbox or bbox[] column
if (
!selectedColumns.find(
({ type }) =>
type.kind === 'BoundingBox' ||
type.kind === 'Category' ||
type.kind === 'Image'
(type.kind === 'Sequence' && type.dtype.kind === 'BoundingBox')
)
) {
if (allowNonSequences) {
allowedColumns.push(
...allColumns.filter(({ type }) => type.kind === 'BoundingBox')
);
});
} else {
return allColumns.filter(({ type }) =>
BoundingBoxLens.dataTypes.includes(type.kind)
);
}
if (allowSequences) {
allowedColumns.push(
...allColumns.filter(
({ type }) =>
type.kind === 'Sequence' && type.dtype.kind === 'BoundingBox'
)
);
}
}
};
BoundingBoxLens.isSatisfied = (columns) => {
if (columns.length < 2) return false;

const types = columns.map((col) => col.type);

if (!types.find((type) => type.kind === 'Image')) return false;

if (!types.find((type) => ['BoundingBox', 'Sequence'].includes(type.kind)))
return false;

// allow exactly one label or label[] column
if (
types.find(
(type) => type.kind === 'Sequence' && type.dtype.kind === 'BoundingBox'
!selectedColumns.find(
({ type }) =>
type.kind === 'Category' ||
type.kind === 'str' ||
(type.kind === 'Sequence' &&
(type.dtype.kind === 'str' || type.dtype.kind === 'Category'))
)
) {
return true;
} else {
if (types.find((type) => type.kind === 'BoundingBox')) return true;
else return false;
if (allowNonSequences) {
allowedColumns.push(
...allColumns.filter(
({ type }) => type.kind === 'Category' || type.kind === 'str'
)
);
}
if (allowSequences) {
allowedColumns.push(
...allColumns.filter(
({ type }) =>
type.kind === 'Sequence' &&
(type.dtype.kind === 'str' || type.dtype.kind === 'Category')
)
);
}
}
return allowedColumns;
};
BoundingBoxLens.isSatisfied = (columns) => {
const types = columns.map((col) => col.type);
const hasImage = !!types.find((type) => type.kind === 'Image');
const hasBbox = !!types.find(
(type) =>
type.kind === 'BoundingBox' ||
(type.kind === 'Sequence' && type.dtype.kind === 'BoundingBox')
);
return hasImage && hasBbox;
};

export default BoundingBoxLens;