You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by er...@apache.org on 2022/01/25 00:38:00 UTC
[commons-math] 08/11: MATH-1580: "K-Means" clustering example.
This is an automated email from the ASF dual-hosted git repository.
erans pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-math.git
commit 565b896873048416f611c12e8667bd76a83f47a6
Author: Gilles Sadowski <gi...@gmail.com>
AuthorDate: Mon Jan 24 18:14:59 2022 +0100
MATH-1580: "K-Means" clustering example.
Adapted application moved to the "commons-math-examples" module.
* GUI dependencies have been removed.
* Any format supported by "Commons Imaging" can be used as input.
* Clustered image saved in PNG format.
---
commons-math-examples/examples-kmeans/LICENCE | 201 ++++++++++++++++++++
commons-math-examples/examples-kmeans/NOTICE | 5 +
.../examples-kmeans/image/LICENCE | 201 ++++++++++++++++++++
commons-math-examples/examples-kmeans/image/NOTICE | 5 +
.../examples-kmeans/image/pom.xml | 69 +++++++
.../math4/examples/kmeans/image/ImageData.java | 151 +++++++++++++++
.../math4/examples/kmeans/image/StandAlone.java | 80 ++++++++
.../math4/examples/kmeans/image/package-info.java | 22 +++
commons-math-examples/examples-kmeans/pom.xml | 57 ++++++
commons-math-examples/pom.xml | 14 +-
.../clustering/ImageClusteringExample.java | 203 ---------------------
src/userguide/resources/ColorfulBird.jpg | Bin 98227 -> 0 bytes
12 files changed, 803 insertions(+), 205 deletions(-)
diff --git a/commons-math-examples/examples-kmeans/LICENCE b/commons-math-examples/examples-kmeans/LICENCE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/LICENCE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/commons-math-examples/examples-kmeans/NOTICE b/commons-math-examples/examples-kmeans/NOTICE
new file mode 100644
index 0000000..28031e8
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/NOTICE
@@ -0,0 +1,5 @@
+Apache Commons Math
+Copyright 2001-2022 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git a/commons-math-examples/examples-kmeans/image/LICENCE b/commons-math-examples/examples-kmeans/image/LICENCE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/image/LICENCE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/commons-math-examples/examples-kmeans/image/NOTICE b/commons-math-examples/examples-kmeans/image/NOTICE
new file mode 100644
index 0000000..28031e8
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/image/NOTICE
@@ -0,0 +1,5 @@
+Apache Commons Math
+Copyright 2001-2022 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git a/commons-math-examples/examples-kmeans/image/pom.xml b/commons-math-examples/examples-kmeans/image/pom.xml
new file mode 100644
index 0000000..1239e5b
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/image/pom.xml
@@ -0,0 +1,69 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>examples-kmeans</artifactId>
+ <version>4.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>examples-kmeans-image</artifactId>
+ <version>4.0-SNAPSHOT</version>
+ <!-- This name is used in the shaded jar to provide the application title for the version information. -->
+ <name>K-Means: Image Clustering</name>
+
+ <description>Clustering applied to 2D graphics data (image).</description>
+
+ <properties>
+ <maven.compiler.source>1.8</maven.compiler.source>
+ <maven.compiler.target>1.8</maven.compiler.target>
+
+ <!-- OSGi -->
+ <commons.osgi.symbolicName>org.apache.commons.math4.examples.kmeans.image</commons.osgi.symbolicName>
+ <commons.osgi.export>org.apache.commons.math4.examples.kmeans.image</commons.osgi.export>
+ <!-- Java 9+ -->
+ <commons.automatic.module.name>org.apache.commons.math4.examples.kmeans.image</commons.automatic.module.name>
+ <!-- Workaround to avoid duplicating config files. -->
+ <math.parent.dir>${basedir}/../../..</math.parent.dir>
+
+ <uberjar.name>examples-kmeans-image</uberjar.name>
+ <project.mainClass>org.apache.commons.math4.examples.kmeans.image.StandAlone</project.mainClass>
+ </properties>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-geometry-euclidean</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-math4-legacy</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-imaging</artifactId>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/ImageData.java b/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/ImageData.java
new file mode 100644
index 0000000..44b98ec
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/ImageData.java
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.math4.examples.kmeans.image;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.awt.image.BufferedImage;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import org.apache.commons.imaging.Imaging;
+import org.apache.commons.imaging.ImageFormat;
+import org.apache.commons.imaging.ImageFormats;
+import org.apache.commons.imaging.ImageReadException;
+import org.apache.commons.imaging.ImageWriteException;
+import org.apache.commons.math4.legacy.ml.clustering.Clusterable;
+import org.apache.commons.math4.legacy.ml.clustering.Cluster;
+
+/**
+ * Retrieve pixel contents from an image file.
+ */
+final class ImageData {
+ /** Image data. */
+ private final Raster data;
+ /** Pixel dataset. */
+ private final List<PixelClusterable> pixels = new ArrayList<>();
+
+ /**
+ * @param image Image.
+ */
+ private ImageData(BufferedImage image) {
+ data = image.getData();
+
+ // Build dataset.
+ for (int row = 0; row < image.getHeight(); row++) {
+ for (int col = 0; col < image.getWidth(); col++) {
+ pixels.add(new PixelClusterable(col, row));
+ }
+ }
+ }
+
+ /**
+ * Load from file.
+ *
+ * @param file Graphics file.
+ * @return a new instance.
+ */
+ static ImageData load(String file) {
+ try {
+ return new ImageData(Imaging.getBufferedImage(new File(file)));
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ } catch (ImageReadException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Create clustered image and write it to a file in PNG format.
+ *
+ * @param clusters Clusters.
+ * @param outputPrefix Prefix of the output file.
+ * Graphics format extension will be appended.
+ */
+ void write(List<? extends Cluster<PixelClusterable>> clusters,
+ String outputPrefix) {
+ final BufferedImage imageC = new BufferedImage(data.getWidth(),
+ data.getHeight(),
+ BufferedImage.TYPE_INT_RGB);
+
+ final WritableRaster raster = imageC.getRaster();
+
+ for (Cluster<PixelClusterable> cluster : clusters) {
+ final double[] color = cluster.centroid().getPoint();
+ for (PixelClusterable pixel : cluster.getPoints()) {
+ raster.setPixel(pixel.x, pixel.y, color);
+ }
+ }
+
+ try {
+ final ImageFormat format = ImageFormats.PNG;
+ Imaging.writeImage(imageC,
+ new File(outputPrefix + format.getDefaultExtension()),
+ format);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ } catch (ImageWriteException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * @return the dataset.
+ */
+ Collection<PixelClusterable> getPixels() {
+ return Collections.unmodifiableCollection(pixels);
+ }
+
+ /**
+ * Bridge that presents a pixel as clusterable data.
+ * Instances are mutable; they keep a reference to the original
+ * image data.
+ */
+ class PixelClusterable implements Clusterable {
+ /** Pixel abscissa. */
+ private final int x;
+ /** Pixel ordinate. */
+ private final int y;
+ /** Pixel color. */
+ private double[] color;
+
+ /**
+ * @param x Abscissa.
+ * @param y Ordinate.
+ */
+ PixelClusterable(int x,
+ int y) {
+ this.x = x;
+ this.y = y;
+ this.color = null;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public double[] getPoint() {
+ if (color == null) {
+ color = data.getPixel(x, y, (double[]) null);
+ }
+ return color;
+ }
+ }
+}
diff --git a/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/StandAlone.java b/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/StandAlone.java
new file mode 100644
index 0000000..9f84a4b
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/StandAlone.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.math4.examples.kmeans.image;
+
+import java.util.concurrent.Callable;
+
+import picocli.CommandLine;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Command;
+
+import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.simple.RandomSource;
+import org.apache.commons.math4.legacy.ml.distance.DistanceMeasure;
+import org.apache.commons.math4.legacy.ml.distance.EuclideanDistance;
+import org.apache.commons.math4.legacy.ml.clustering.Clusterer;
+import org.apache.commons.math4.legacy.ml.clustering.KMeansPlusPlusClusterer;
+
+/**
+ * Application class.
+ */
+@Command(description = "Run the application",
+ mixinStandardHelpOptions = true)
+public final class StandAlone implements Callable<Void> {
+ /** The k parameter. */
+ @Option(names = { "-k" }, paramLabel = "K", required = true,
+ description = "Number of clusters.")
+ private int numClusters;
+ /** The maximal number of iterations. */
+ @Option(names = { "-i", "--iterations" }, paramLabel = "N",
+ description = "Allowed number of iterations (default: ${DEFAULT-VALUE}).")
+ private int maxIter = 2000;
+ /** The input file. */
+ @Option(names = { "--image" }, paramLabel = "FILE", required = true,
+ description = "Input file name.")
+ private String inputFile;
+ /** The output prefix. */
+ @Option(names = { "-o", "--output" }, paramLabel = "PREFIX", required = true,
+ description = "Prefix (path) for the output files.")
+ private String outputPrefix;
+
+ /**
+ * Program entry point.
+ *
+ * @param args Command line arguments and options.
+ */
+ public static void main(String[] args) {
+ CommandLine.call(new StandAlone(), args);
+ }
+
+ @Override
+ public Void call() {
+ final ImageData image = ImageData.load(inputFile);
+ final UniformRandomProvider rng = RandomSource.MWC_256.create();
+ final DistanceMeasure distance = new EuclideanDistance();
+ final Clusterer<ImageData.PixelClusterable> algo =
+ new KMeansPlusPlusClusterer<>(numClusters,
+ maxIter,
+ distance,
+ rng);
+ image.write(algo.cluster(image.getPixels()),
+ outputPrefix + ".k_" + numClusters + ".kmeans.");
+
+ return null;
+ }
+}
diff --git a/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/package-info.java b/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/package-info.java
new file mode 100644
index 0000000..df8e6b2
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/image/src/main/java/org/apache/commons/math4/examples/kmeans/image/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Clustering a 2D graphics (image).
+ */
+
+package org.apache.commons.math4.examples.kmeans.image;
diff --git a/commons-math-examples/examples-kmeans/pom.xml b/commons-math-examples/examples-kmeans/pom.xml
new file mode 100644
index 0000000..b40f5b9
--- /dev/null
+++ b/commons-math-examples/examples-kmeans/pom.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-math-examples</artifactId>
+ <version>4.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>examples-kmeans</artifactId>
+ <version>4.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+ <name>K-Means</name>
+
+ <description>K-Means++ clustering sample codes.</description>
+
+ <properties>
+ <!-- Workaround to avoid duplicating config files. -->
+ <math.parent.dir>${basedir}/../..</math.parent.dir>
+ </properties>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-math4-legacy</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>info.picocli</groupId>
+ <artifactId>picocli</artifactId>
+ </dependency>
+
+ </dependencies>
+
+ <modules>
+ <module>image</module>
+ </modules>
+
+</project>
diff --git a/commons-math-examples/pom.xml b/commons-math-examples/pom.xml
index e89d8f6..ccef4d6 100644
--- a/commons-math-examples/pom.xml
+++ b/commons-math-examples/pom.xml
@@ -29,8 +29,10 @@
<packaging>pom</packaging>
<name>Example applications</name>
- <description>Examples of use of the "Commons Math" library.
- Codes in this module and its sub-modules are not part of the public API.
+ <description>
+ Usage examples of the "Commons Math" library.
+ Codes in this module and its sub-modules are not part of the library's API;
+ they can be updated or removed at any time.
</description>
<properties>
@@ -49,6 +51,7 @@
<math.picocli.version>3.9.5</math.picocli.version>
<math.rng.version>1.4</math.rng.version>
<math.geometry.version>1.0</math.geometry.version>
+ <math.imaging.version>1.0-alpha3-SNAPSHOT</math.imaging.version>
<!-- Disable JApiCmp failures (but keep the report). The examples API is allowed to change. -->
<commons.japicmp.breakBuildOnBinaryIncompatibleModifications>false</commons.japicmp.breakBuildOnBinaryIncompatibleModifications>
@@ -90,6 +93,12 @@
</dependency>
<dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-imaging</artifactId>
+ <version>${math.imaging.version}</version>
+ </dependency>
+
+ <dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>${math.picocli.version}</version>
@@ -158,6 +167,7 @@
<modules>
<module>examples-sofm</module>
+ <module>examples-kmeans</module>
</modules>
</project>
diff --git a/src/userguide/java/org/apache/commons/math4/userguide/clustering/ImageClusteringExample.java b/src/userguide/java/org/apache/commons/math4/userguide/clustering/ImageClusteringExample.java
deleted file mode 100644
index 67e197a..0000000
--- a/src/userguide/java/org/apache/commons/math4/userguide/clustering/ImageClusteringExample.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math4.userguide.clustering;
-
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-import java.awt.Graphics;
-import java.awt.GridLayout;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.image.BufferedImage;
-import java.awt.image.Raster;
-import java.awt.image.WritableRaster;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.imageio.ImageIO;
-import javax.swing.BorderFactory;
-import javax.swing.Box;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JSpinner;
-import javax.swing.SpinnerNumberModel;
-
-import org.apache.commons.math4.ml.clustering.CentroidCluster;
-import org.apache.commons.math4.ml.clustering.Clusterable;
-import org.apache.commons.math4.ml.clustering.KMeansPlusPlusClusterer;
-import org.apache.commons.math4.userguide.ExampleUtils;
-import org.apache.commons.math4.userguide.ExampleUtils.ExampleFrame;
-
-/**
- * This example shows how clustering can be applied to images.
- */
-@SuppressWarnings("serial")
-public class ImageClusteringExample {
-
- public static class Display extends ExampleFrame {
-
- private BufferedImage referenceImage;
- private BufferedImage clusterImage;
-
- private Raster referenceRaster;
-
- private ImagePainter painter;
-
- private JSpinner clusterSizeSpinner;
-
- public Display() throws Exception {
- setTitle("Commons-Math: Image Clustering Example");
- setSize(900, 350);
-
- setLayout(new FlowLayout());
-
- Box bar = Box.createHorizontalBox();
-
- referenceImage = ExampleUtils.resizeImage(
- ImageIO.read(new File("resources/ColorfulBird.jpg")),
- 350,
- 240,
- BufferedImage.TYPE_INT_RGB);
-
- referenceRaster = referenceImage.getData();
-
- clusterImage = new BufferedImage(referenceImage.getWidth(),
- referenceImage.getHeight(),
- BufferedImage.TYPE_INT_RGB);
-
- JLabel picLabel = new JLabel(new ImageIcon(referenceImage));
- bar.add(picLabel);
-
- painter = new ImagePainter(clusterImage.getWidth(), clusterImage.getHeight());
- bar.add(painter);
-
- JPanel controlBox = new JPanel();
- controlBox.setLayout(new GridLayout(5, 1));
- controlBox.setBorder(BorderFactory.createLineBorder(Color.black, 1));
-
- JPanel sizeBox = new JPanel();
- JLabel sizeLabel = new JLabel("Clusters:");
- sizeBox.add(sizeLabel);
-
- SpinnerNumberModel model = new SpinnerNumberModel(3, 2, 10, 1);
- clusterSizeSpinner = new JSpinner(model);
-
- sizeLabel.setLabelFor(clusterSizeSpinner);
- sizeBox.add(clusterSizeSpinner);
- controlBox.add(sizeBox, BorderLayout.NORTH);
-
- JButton startButton = new JButton("Cluster");
- startButton.setActionCommand("cluster");
- controlBox.add(startButton, BorderLayout.CENTER);
-
- bar.add(controlBox);
-
- add(bar);
-
- startButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- clusterImage();
- }
- });
- }
-
- private void clusterImage() {
- List<PixelClusterable> pixels = new ArrayList<PixelClusterable>();
- for (int row = 0; row < referenceImage.getHeight(); row++) {
- for (int col = 0; col < referenceImage.getWidth(); col++) {
- pixels.add(new PixelClusterable(col, row));
- }
- }
-
- int clusterSize = ((Number) clusterSizeSpinner.getValue()).intValue();
- KMeansPlusPlusClusterer<PixelClusterable> clusterer =
- new KMeansPlusPlusClusterer<PixelClusterable>(clusterSize);
- List<CentroidCluster<PixelClusterable>> clusters = clusterer.cluster(pixels);
-
- WritableRaster raster = clusterImage.getRaster();
- for (CentroidCluster<PixelClusterable> cluster : clusters) {
- double[] color = cluster.getCenter().getPoint();
- for (PixelClusterable pixel : cluster.getPoints()) {
- raster.setPixel(pixel.x, pixel.y, color);
- }
- }
-
- Display.this.repaint();
- }
-
- private class PixelClusterable implements Clusterable {
-
- private final int x;
- private final int y;
- private double[] color;
-
- public PixelClusterable(int x, int y) {
- this.x = x;
- this.y = y;
- this.color = null;
- }
-
- @Override
- public double[] getPoint() {
- if (color == null) {
- color = referenceRaster.getPixel(x, y, (double[]) null);
- }
- return color;
- }
-
- }
-
- private class ImagePainter extends Component {
-
- private int width;
- private int height;
-
- public ImagePainter(int width, int height) {
- this.width = width;
- this.height = height;
- }
-
- public Dimension getPreferredSize() {
- return new Dimension(width, height);
- }
-
- @Override
- public Dimension getMinimumSize() {
- return getPreferredSize();
- }
-
- @Override
- public Dimension getMaximumSize() {
- return getPreferredSize();
- }
-
- public void paint(Graphics g) {
- g.drawImage(clusterImage, 0, 0, this);
- }
- }
- }
-
- public static void main(String[] args) throws Exception {
- ExampleUtils.showExampleFrame(new Display());
- }
-}
diff --git a/src/userguide/resources/ColorfulBird.jpg b/src/userguide/resources/ColorfulBird.jpg
deleted file mode 100644
index 5753596..0000000
Binary files a/src/userguide/resources/ColorfulBird.jpg and /dev/null differ