View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  package org.hipparchus.samples.clustering;
23  
24  import java.awt.BorderLayout;
25  import java.awt.Color;
26  import java.awt.Component;
27  import java.awt.Dimension;
28  import java.awt.FlowLayout;
29  import java.awt.Graphics;
30  import java.awt.GridLayout;
31  import java.awt.image.BufferedImage;
32  import java.awt.image.Raster;
33  import java.awt.image.WritableRaster;
34  import java.io.IOException;
35  import java.util.ArrayList;
36  import java.util.List;
37  
38  import javax.imageio.ImageIO;
39  import javax.swing.BorderFactory;
40  import javax.swing.Box;
41  import javax.swing.ImageIcon;
42  import javax.swing.JButton;
43  import javax.swing.JLabel;
44  import javax.swing.JPanel;
45  import javax.swing.JSpinner;
46  import javax.swing.SpinnerNumberModel;
47  
48  import org.hipparchus.clustering.CentroidCluster;
49  import org.hipparchus.clustering.Clusterable;
50  import org.hipparchus.clustering.KMeansPlusPlusClusterer;
51  import org.hipparchus.samples.ExampleUtils;
52  import org.hipparchus.samples.ExampleUtils.ExampleFrame;
53  
54  /**
55   * This example shows how clustering can be applied to images.
56   */
57  //CHECKSTYLE: stop HideUtilityClassConstructor
58  @SuppressWarnings("serial")
59  public class ImageClusteringExample {
60  
61      /** Empty constructor.
62       * <p>
63       * This constructor is not strictly necessary, but it prevents spurious
64       * javadoc warnings with JDK 18 and later.
65       * </p>
66       * @since 3.0
67       */
68      public ImageClusteringExample() { // NOPMD - unnecessary constructor added intentionally to make javadoc happy
69          // nothing to do
70      }
71  
72      /** Main frame for displaying clusters. */
73      public static class Display extends ExampleFrame {
74  
75          /** Reference image. */
76          private BufferedImage referenceImage;
77  
78          /** Cluster image. */
79          private BufferedImage clusterImage;
80  
81          /** Reference raster. */
82          private Raster referenceRaster;
83  
84          /** Painter for the clusters. */
85          private ImagePainter painter;
86  
87          /** Spinner. */
88          private JSpinner clusterSizeSpinner;
89  
90          /** Simple constructor.
91           * @throws IOException if image cannot be created
92           */
93          public Display() throws IOException {
94              setTitle("Hipparchus: Image Clustering Example");
95              setSize(900, 350);
96  
97              setLayout(new FlowLayout());
98  
99              Box bar = Box.createHorizontalBox();
100 
101             ClassLoader classLoader = ExampleUtils.class.getClassLoader();
102             referenceImage = ExampleUtils.resizeImage(
103                     ImageIO.read(classLoader.getResourceAsStream("ColorfulBird.jpg")),
104                     350,
105                     240,
106                     BufferedImage.TYPE_INT_RGB);
107 
108             referenceRaster = referenceImage.getData();
109 
110             clusterImage = new BufferedImage(referenceImage.getWidth(),
111                                              referenceImage.getHeight(),
112                                              BufferedImage.TYPE_INT_RGB);
113 
114             JLabel picLabel = new JLabel(new ImageIcon(referenceImage));
115             bar.add(picLabel);
116 
117             painter = new ImagePainter(clusterImage.getWidth(), clusterImage.getHeight());
118             bar.add(painter);
119 
120             JPanel controlBox = new JPanel();
121             controlBox.setLayout(new GridLayout(5, 1));
122             controlBox.setBorder(BorderFactory.createLineBorder(Color.black, 1));
123 
124             JPanel sizeBox = new JPanel();
125             JLabel sizeLabel = new JLabel("Clusters:");
126             sizeBox.add(sizeLabel);
127 
128             SpinnerNumberModel model = new SpinnerNumberModel(3, 2, 10, 1);
129             clusterSizeSpinner = new JSpinner(model);
130 
131             sizeLabel.setLabelFor(clusterSizeSpinner);
132             sizeBox.add(clusterSizeSpinner);
133             controlBox.add(sizeBox, BorderLayout.NORTH);
134 
135             JButton startButton = new JButton("Cluster");
136             startButton.setActionCommand("cluster");
137             controlBox.add(startButton, BorderLayout.CENTER);
138 
139             bar.add(controlBox);
140 
141             add(bar);
142 
143             startButton.addActionListener(e -> clusterImage());
144         }
145 
146         /** Display clusters.
147          */
148         private void clusterImage() {
149             List<PixelClusterable> pixels = new ArrayList<>();
150             for (int row = 0; row < referenceImage.getHeight(); row++) {
151                 for (int col = 0; col < referenceImage.getWidth(); col++) {
152                     pixels.add(new PixelClusterable(col, row));
153                 }
154             }
155 
156             int clusterSize = ((Number) clusterSizeSpinner.getValue()).intValue();
157             KMeansPlusPlusClusterer<PixelClusterable> clusterer =
158                     new KMeansPlusPlusClusterer<>(clusterSize);
159             List<CentroidCluster<PixelClusterable>> clusters = clusterer.cluster(pixels);
160 
161             WritableRaster raster = clusterImage.getRaster();
162             for (CentroidCluster<PixelClusterable> cluster : clusters) {
163                 double[] color = cluster.getCenter().getPoint();
164                 for (PixelClusterable pixel : cluster.getPoints()) {
165                     raster.setPixel(pixel.x, pixel.y, color);
166                 }
167             }
168 
169             Display.this.repaint();
170         }
171 
172         /** Container for one pixel that can be used in clusters. */
173         private class PixelClusterable implements Clusterable {
174 
175             /** Abscissa. */
176             private final int x;
177 
178             /** Ordinate. */
179             private final int y;
180 
181             /** Color. */
182             private double[] color;
183 
184             /** Simple constructor.
185              * @param x abscissa
186              * @param y ordinate
187              */
188             PixelClusterable(int x, int y) {
189                 this.x = x;
190                 this.y = y;
191                 this.color = null;
192             }
193 
194             /** {@inheritDoc} */
195             @Override
196             public double[] getPoint() {
197                 if (color == null) {
198                     color = referenceRaster.getPixel(x, y, (double[]) null);
199                 }
200                 return color;
201             }
202 
203         }
204 
205         /** Painter for clusters. */
206         private class ImagePainter extends Component {
207 
208             /** Width. */
209             private int width;
210 
211             /** Height. */
212             private int height;
213 
214             /** Simple constructor.
215              * @param width width
216              * @param height height
217              */
218             ImagePainter(int width, int height) {
219                 this.width = width;
220                 this.height = height;
221             }
222 
223             /** {@inheritDoc} */
224             @Override
225             public Dimension getPreferredSize() {
226                 return new Dimension(width, height);
227             }
228 
229             /** {@inheritDoc} */
230             @Override
231             public Dimension getMinimumSize() {
232                 return getPreferredSize();
233             }
234 
235             /** {@inheritDoc} */
236             @Override
237             public Dimension getMaximumSize() {
238                 return getPreferredSize();
239             }
240 
241             /** {@inheritDoc} */
242             @Override
243             public void paint(Graphics g) {
244                 g.drawImage(clusterImage, 0, 0, this);
245             }
246 
247         }
248 
249     }
250 
251     /** Program entry point.
252      * @param args program arguments (unused here)
253      * @throws IOException if display frame cannot be created.
254      */
255     public static void main(String[] args) throws IOException {
256         ExampleUtils.showExampleFrame(new Display());
257     }
258 
259 }