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

Add connectedComponents to MagickImage #114

Merged
merged 14 commits into from
Nov 7, 2023
86 changes: 86 additions & 0 deletions src/connected-component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright Dirk Lemstra https://github.com/dlemstra/magick-wasm.
// Licensed under the Apache License, Version 2.0.

import { ImageMagick } from './image-magick';
import { MagickColor } from './magick-color';
import { MagickGeometry } from './magick-geometry';
import { Point } from './point';

/**
* An ImageMagick connected component object.
*/
export class ConnectedComponent {
/**
* The pixel count of the area.
*/
readonly area: number;
/**
* The centroid of the area.
*/
readonly centroid: Point;
/**
* The color of the area.
*/
readonly color?: MagickColor;
/**
* The height of the area.
*/
readonly height: number;
/**
* The id of the area.
*/
readonly id: number;
/**
* The width of the area.
*/
readonly width: number;
/**
* The X offset from origin.
*/
readonly x: number;
/**
* The Y offset from origin.
*/
readonly y: number;

constructor(instance: number) {
with-heart marked this conversation as resolved.
Show resolved Hide resolved
this.area = ImageMagick._api._ConnectedComponent_GetArea(instance);
this.centroid = Point._create(ImageMagick._api._ConnectedComponent_GetCentroid(instance));
this.color = MagickColor._create(ImageMagick._api._ConnectedComponent_GetColor(instance));
this.height = ImageMagick._api._ConnectedComponent_GetHeight(instance);
this.id = ImageMagick._api._ConnectedComponent_GetId(instance);
this.width = ImageMagick._api._ConnectedComponent_GetWidth(instance);
this.x = ImageMagick._api._ConnectedComponent_GetX(instance);
this.y = ImageMagick._api._ConnectedComponent_GetY(instance);
}

/** @internal */
static _create(list: number, length: number): ReadonlyArray<ConnectedComponent> {
const result: ConnectedComponent[] = [];

if (list === 0) {
return result;
}

for (let i = 0; i < length; i++) {
const instance = ImageMagick._api._ConnectedComponent_GetInstance(list, i);

if (instance === 0) {
continue;
}

with-heart marked this conversation as resolved.
Show resolved Hide resolved
result.push(new ConnectedComponent(instance));
}

return result;
}

/**
* Returns the geometry of the area of the connected component.
*/
toGeometry(extent: number = 0): MagickGeometry {
with-heart marked this conversation as resolved.
Show resolved Hide resolved
const extra = extent * 2;

return new MagickGeometry(this.x - extent, this.y - extent, this.width + extra, this.height + extra);
}
}
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from './color-space';
export * from './color-type';
export * from './composite-operator';
export * from './compression-method';
export * from './connected-component';
export * from './defines/define';
export * from './defines/defines-creator';
export * from './defines/defines';
Expand Down Expand Up @@ -74,6 +75,7 @@ export * from './point';
export * from './primary-info';
export * from './profiles/image-profile';
export * from './quantum';
export * from './settings/connected-components-settings';
export * from './settings/distort-settings';
export * from './settings/drawing-settings';
export * from './settings/magick-read-settings';
Expand All @@ -83,4 +85,5 @@ export * from './settings/morphology-settings';
export * from './statistics';
export * from './text-alignment';
export * from './text-decoration';
export * from './threshold';
export * from './virtual-pixel-method';
57 changes: 57 additions & 0 deletions src/magick-image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ColorSpace } from './color-space';
import { ColorType } from './color-type';
import { CompositeOperator } from './composite-operator';
import { CompressionMethod } from './compression-method';
import { ConnectedComponent } from './connected-component';
import { Density } from './density';
import { Disposable } from './internal/disposable';
import { DisposableArray } from './internal/disposable-array';
Expand Down Expand Up @@ -49,6 +50,7 @@ import { Point } from './point';
import { Pointer } from './internal/pointer/pointer';
import { PrimaryInfo } from './primary-info';
import { Quantum } from './quantum';
import { ConnectedComponentsSettings, Connectivity } from './settings/connected-components-settings';
import { Statistics, IStatistics } from './statistics';
import { StringInfo } from './internal/string-info';
import { VirtualPixelMethod } from './virtual-pixel-method';
Expand Down Expand Up @@ -152,6 +154,35 @@ export interface IMagickImage extends IDisposable {
compositeGravity(image: IMagickImage, gravity: Gravity, compose: CompositeOperator, point: Point, channels: Channels): void;
compositeGravity(image: IMagickImage, gravity: Gravity, compose: CompositeOperator, point: Point, args: string): void;
compositeGravity(image: IMagickImage, gravity: Gravity, compose: CompositeOperator, point: Point, args: string, channels: Channels): void;
/**
* Determines the connected-components of the image.
*
* @param connectivity The number of neighbors to visit (4 or 8).
* @see {@link https://imagemagick.org/script/connected-components.php}
*
* @example
Copy link
Owner

@dlemstra dlemstra Oct 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if I want to keep this here because that would also require me to maintain it. A description of the method and parameters and the @see should be sufficient?

And should we not add this documentation to the interface instead?

Copy link
Contributor Author

@with-heart with-heart Nov 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if I want to keep this here because that would also require me to maintain it.

Yeah that's totally fair. Maintenance concerns are always a good reason to be wary of too much "extra" stuff.

I think @example theoretically shouldn't be much of a maintenance concern though, at least in this case:

  • the examples aren't very complex (just showing basic usage and return type)
  • the IMagickImage api likely won't change drastically

A description of the method and parameters and the @see should be sufficient?

I feel like it's a good first-touch bit of context for users on how to use this in a js-specific setting. Descriptions tell you what it does, @see gives extra information like the various defines available, but @example shows how to use it in js specifically.

Just sharing my thoughts though! If it still feels like something you'd prefer to not have to think about, will gladly remove

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will remove them myself after merging the PR. I think we should put the examples somewhere else.

* declare const image: MagickImage;
* const components = image.connectedComponents(4);
* // ^? ReadonlyArray<ConnectedComponent>
*/
connectedComponents(connectivity: Connectivity): ReadonlyArray<ConnectedComponent>;
/**
* Determines the connected-components of the image.
*
* @param settings The connected-components operation settings.
* @see {@link https://imagemagick.org/script/connected-components.php}
*
* @example
* declare const image: MagickImage;
*
* const settings = new ConnectedComponentsSettings(4);
* settings.areaThreshold = new Threshold(50);
* settings.meanColor = true;
*
* const components = image.connectedComponents(settings);
* // ^? ReadonlyArray<ConnectedComponent>
*/
connectedComponents(settings: ConnectedComponentsSettings): ReadonlyArray<ConnectedComponent>;
contrast(): void;
contrastStretch(blackPoint: Percentage): void;
contrastStretch(blackPoint: Percentage, whitePoint: Percentage): void;
Expand Down Expand Up @@ -792,6 +823,32 @@ export class MagickImage extends NativeInstance implements IMagickImage {
this.removeArtifact('compose:args');
}

connectedComponents(connectivity: Connectivity): ReadonlyArray<ConnectedComponent>;
connectedComponents(settings: ConnectedComponentsSettings): ReadonlyArray<ConnectedComponent>;
connectedComponents(connectivityOrSettings: Connectivity | ConnectedComponentsSettings): ReadonlyArray<ConnectedComponent> {
const settings = typeof connectivityOrSettings === 'number' ? new ConnectedComponentsSettings(connectivityOrSettings) : connectivityOrSettings;

settings._setArtifacts(this);

const connectedComponents = Exception.use((exception) => {
return Pointer.use((objects) => {
try {
const instance = ImageMagick._api._MagickImage_ConnectedComponents(this._instance, settings.connectivity, objects.ptr, exception.ptr);
const colormapSize = ImageMagick._api._MagickImage_ColormapSize_Get(instance, exception.ptr);

return ConnectedComponent._create(objects.value, colormapSize);
} finally {
if (objects.value !== 0) {
ImageMagick._api._ConnectedComponent_DisposeList(objects.value);
}
}
});
});

settings._removeArtifacts(this);
return connectedComponents;
}

contrast = () => this._contrast(true);

contrastStretch(blackPoint: Percentage): void;
Expand Down
9 changes: 9 additions & 0 deletions src/point.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright Dirk Lemstra https://github.com/dlemstra/magick-wasm.
// Licensed under the Apache License, Version 2.0.

import { ImageMagick } from "./image-magick";

export class Point {
private _x: number;
private _y: number;
Expand All @@ -17,4 +19,11 @@ export class Point {

get y(): number { return this._y; }
set y(value: number) { this._y = value; }

/** @internal */
static _create(instance: number): Point {
if (instance === 0) return new Point(0, 0);
with-heart marked this conversation as resolved.
Show resolved Hide resolved

return new Point(ImageMagick._api._PointInfo_X_Get(instance), ImageMagick._api._PointInfo_Y_Get(instance));
}
}
132 changes: 132 additions & 0 deletions src/settings/connected-components-settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Copyright Dirk Lemstra https://github.com/dlemstra/magick-wasm.
// Licensed under the Apache License, Version 2.0.

import { IMagickImage } from '../magick-image';
import { Threshold } from '../threshold';

/**
* Represents the number of neighbors to visit in the connected components
* operation (4 or 8).
*/
export type Connectivity = 4 | 8;

/**
* Settings for the connected components operation.
*/
export class ConnectedComponentsSettings {
/**
* The threshold that merges any object not within the min and max angle
* threshold.
**/
angleThreshold?: Threshold;
/**
* The threshold that eliminates small objects by merging them with their
* larger neighbors.
*/
areaThreshold?: Threshold;
/**
* The threshold that merges any object not within the min and max
* circularity threshold.
*/
circularityThreshold?: Threshold;
/**
* The number of neighbors to visit (4 or 8).
*/
connectivity: Connectivity;
/**
* The threshold that merges any object not within the min and max diameter
* threshold.
*/
diameterThreshold?: Threshold;
/**
* The threshold that merges any object not within the min and max
* eccentricity threshold.
*/
eccentricityThreshold?: Threshold;
/**
* The threshold that merges any object not within the min and max ellipse
* major threshold.
*/
majorAxisThreshold?: Threshold;
/**
* Whether the object color in the component labeled image will be replaced
* with the mean color from the source image (defaults to grayscale).
*/
meanColor?: boolean;
/**
* The threshold that merges any object not within the min and max ellipse
* minor threshold.
*/
minorAxisThreshold?: Threshold;
/**
* The threshold that merges any object not within the min and max perimeter
* threshold.
*/
perimeterThreshold?: Threshold;

constructor(connectivity: Connectivity) {
this.connectivity = connectivity;
}

/** @internal */
_removeArtifacts(image: IMagickImage): void {
if (this.angleThreshold !== undefined) {
image.removeArtifact('connected-components:angle-threshold');
}
if (this.areaThreshold !== undefined) {
image.removeArtifact('connected-components:area-threshold');
}
if (this.circularityThreshold !== undefined) {
image.removeArtifact('connected-components:circularity-threshold');
}
if (this.diameterThreshold !== undefined) {
image.removeArtifact('connected-components:diameter-threshold');
}
if (this.eccentricityThreshold !== undefined) {
image.removeArtifact('connected-components:eccentricity-threshold');
}
if (this.majorAxisThreshold !== undefined) {
image.removeArtifact('connected-components:major-axis-threshold');
}
if (this.meanColor !== undefined) {
image.removeArtifact('connected-components:mean-color');
}
if (this.minorAxisThreshold !== undefined) {
image.removeArtifact('connected-components:minor-axis-threshold');
}
if (this.perimeterThreshold !== undefined) {
image.removeArtifact('connected-components:perimeter-threshold');
}
}

/** @internal */
_setArtifacts(image: IMagickImage): void {
if (this.angleThreshold !== undefined) {
image.setArtifact('connected-components:angle-threshold', this.angleThreshold.toString());
}
if (this.areaThreshold !== undefined) {
image.setArtifact('connected-components:area-threshold', this.areaThreshold.toString());
}
if (this.circularityThreshold !== undefined) {
image.setArtifact('connected-components:circularity-threshold', this.circularityThreshold.toString());
}
if (this.diameterThreshold !== undefined) {
image.setArtifact('connected-components:diameter-threshold', this.diameterThreshold.toString());
}
if (this.eccentricityThreshold !== undefined) {
image.setArtifact('connected-components:eccentricity-threshold', this.eccentricityThreshold.toString());
}
if (this.majorAxisThreshold !== undefined) {
image.setArtifact('connected-components:major-axis-threshold', this.majorAxisThreshold.toString());
}
if (this.meanColor !== undefined) {
image.setArtifact('connected-components:mean-color', this.meanColor.toString());
}
if (this.minorAxisThreshold !== undefined) {
image.setArtifact('connected-components:minor-axis-threshold', this.minorAxisThreshold.toString());
}
if (this.perimeterThreshold !== undefined) {
image.setArtifact('connected-components:perimeter-threshold', this.perimeterThreshold.toString());
}
}
}
35 changes: 35 additions & 0 deletions src/threshold.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright Dirk Lemstra https://github.com/dlemstra/magick-wasm.
// Licensed under the Apache License, Version 2.0.

/**
* Represents a threshold with a minimum and (optional) maximum value.
*/
export class Threshold {
constructor(
/** The minimum value of the threshold. */
readonly minimum: number,
/** The maximum value of the threshold (or 0 if no maximum). */
readonly maximum: number = 0,
) {}

/**
* Convert the threshold to a string.
*
* @example
* // no maximum
* const threshold = new Threshold(50);
* threshold.toString(); // '50'
*
* @example
* // with maximum
* const threshold = new Threshold(50, 100);
* threshold.toString(); // '50-100'
*/
toString(): string {
if (this.maximum === 0) {
return this.minimum.toString();
} else {
return `${this.minimum}-${this.maximum}`;
}
}
}
Loading