How to get max 5 color from image??

I try to get max 5 color from image (ex. jpeg,gif) ,I use PixelGrabber
it too slowly when i use large image,Please help me, to run more fast
(other way PixelGrabber)
best regard
[email protected],[email protected]
source below:
public String generateColor(InputStream source,String filePath){
BufferedImage image = null;
String RGB = "";
System.out.println("==generateColor==");
try {
image = ImageIO.read(source);
catch (IOException ex1) {
ex1.printStackTrace();
//image.getGraphics().getColor().get
// BufferedImage image2 = ImageIO.read(source);
// image.getColorModel().getNumColorComponents()
if(image.getColorModel() instanceof IndexColorModel) {
IndexColorModel icm = (IndexColorModel)image.getColorModel();
byte[][] data = new byte[3][icm.getMapSize()];
int[] rgbB = new int[icm.getMapSize()];
icm.getRGBs(rgbB);
String dataHtm = "<HTML><table width=\"100\" border=\"0\"><tr>";
for(int i = 0 ;i< rgbB.length;i++){
int r = (rgbB[i] >> 16) & 0xff;
int g = (rgbB[i] >> 8) & 0xff;
int k = (rgbB) & 0xff;
System.out.println("red:" + Integer.toHexString(r));
System.out.println("green:" + Integer.toHexString(g));
System.out.println("blue:" + Integer.toHexString(k));
dataHtm = dataHtm + "<td width=\"10\" bgcolor=\"#" + Integer.toHexString(r)+Integer.toHexString(g)+Integer.toHexString(k);
dataHtm = dataHtm + "\"> </td>";
dataHtm = dataHtm + "</tr></table></HTML>";
try {
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\23289207.html"));
out.write(dataHtm);
out.close();
catch (IOException e) {
e.printStackTrace();
int w = image.getWidth();
int h = image.getHeight();
int[] pixels = new int[w*h];
int[] pixs = new int[w*h];
System.out.println("image width:"+w+"image hight:"+h+"image w*h:"+(w*h));
Image img = Toolkit.getDefaultToolkit().getImage(filePath);
PixelGrabber pg = new PixelGrabber(img, 0,0, w, h, pixels, 0, w);
try {
pg.grabPixels();
catch (Exception x) {
x.printStackTrace();
String picColor = "";
Stack stackColor = new Stack();
Hashtable hashColor = new Hashtable();
for (int i = 0; i < w * h; i++) {
int rgb = pixels[i];
int a = (rgb >> 24) & 0xff;
int r = (rgb >> 16) & 0xff;
int g = (rgb >> 8) & 0xff;
int k = (rgb) & 0xff;
i = i+1000;
//System.out.println("i:" + i);
picColor = convertToSring(r)+convertToSring(g)+convertToSring(k);
stackColor.add(picColor);
//System.out.println("picColor:"+picColor);
// System.out.println("\n\n a:" + a);
// System.out.println("red:" + r);
// System.out.println("green:" + g);
// System.out.println("blue:" + k);
}//end for
getMaxColor(stackColor);
System.out.println("==generateColor==end\n\n");
return null;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class HighFive
    private void examineColors(BufferedImage image)
        long start = System.currentTimeMillis();
        int w = image.getWidth(), h = image.getHeight();
        int[] rgbs = image.getRGB(0,0,w,h,null,0,w);
        findHighFive(rgbs);
        long end = System.currentTimeMillis();
        System.out.println("total time = " + (end - start)/1000.0 + " seconds");
    private void findHighFive(int[] colors)
        int[] uniqueColors = getUniqueColors(colors);
        int[] colorCounts  = getColorCounts(uniqueColors, colors);
        int[] highFive     = getHighFive(colorCounts);
        // for each value of highFive find index in colorCounts
        // and use this index to find color code in uniqueColors
        for(int j = 0; j < highFive.length; j++)
            int index = findIndexInArray(colorCounts, highFive[j]);
            Color color = new Color(uniqueColors[index]);
            String s = color.toString();
            s = s.substring(s.indexOf("["));
            System.out.println("color " + s + "  occurs " +
                                highFive[j] + " times");
    private int[] getUniqueColors(int[] colors)
        // collect unique colors
        int[] uniqueColors = new int[colors.length];
        int count = 0;
        for(int j = 0; j < colors.length; j++)
            if(isUnique(uniqueColors, colors[j]))
                uniqueColors[count++] = colors[j];
        // trim uniqueColors
        int[] temp = new int[count];
        System.arraycopy(uniqueColors, 0, temp, 0, count);
        uniqueColors = temp;
        return uniqueColors;
    private int[] getColorCounts(int[] uniqueColors, int[] colors)
        // count the occurance of each unique color in colors
        int[] colorCounts = new int[uniqueColors.length];
        for(int j = 0; j < colors.length; j++)
            int index = findIndexInArray(uniqueColors, colors[j]);
            colorCounts[index]++;
        return colorCounts;
    private int[] getHighFive(int[] colorCounts)
        // find five highest values in colorCounts
        int[] highFive = new int[5];
        int count = 0;
        for(int j = 0; j < highFive.length; j++)
            int max = Integer.MIN_VALUE;
            for(int k = 0; k < colorCounts.length; k++)
                if(colorCounts[k] > max)
                    if(isUnique(highFive, colorCounts[k]))
                        max = colorCounts[k];
                        highFive[count] = colorCounts[k];
            count++;
        return highFive;
    private boolean isUnique(int[] n, int target)
        for(int j = 0; j < n.length; j++)
            if(n[j] == target)
                return false;
        return true;
    private int findIndexInArray(int[] n, int target)
        for(int j = 0; j < n.length; j++)
            if(n[j] == target)
                return j;
        return -1;
    public static void main(String[] args) throws IOException
        String path = "images/cougar.jpg";
        Object o = HighFive.class.getResource(path);
        BufferedImage image = ImageIO.read(((URL)o).openStream());
        new HighFive().examineColors(image);
}

Similar Messages

  • How to get name of color from Color class

    Hi there,
    I'm just starting my adventure with java and just on the beginning of this trip I found some issue.
    How to get something like this:
    String getColorName(Color var) { ??? }
    String test = getColorName(Color.RED); // test = "red"; or test = "RED";Thank in advance for some constructive ideas

    profidancer wrote:
    dcminter, would You say it in other words, because I'm not following You.
    Do You mean by that to create class like below with some connection inside ??
    public class ColorMap {
         private String name;
         private Color color;
    public String toString() {
         return name;
    I suppose that's one way to do it. Or you could just use the [Map |http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html] interface.
    Another option is to simply make the JButton the color it represents, instead of displaying some String with a color name. That way you could support any color pretty easily.

  • How to get Coordinates of edges from image into excel

    Hi,
    I am new to labview and I am doing a project in which i move an XY stage under a laser to etch pictures.  So far I have managed to get the stage to move by reading off coordinates from an excel spread sheet and so can draw pictures if I have the coordinates.
     I am trying to use the vision module to be able to put any image in and then find the edges, get the coordinates of the edge and so draw the image.  Using the vision assistant I do colour plane extraction (to make greyscale) then use shape detection looking for lines with a small minimum length, this gets the information i want and if i click the button on the right that says send data to excell i get a spread sheet with all the information i need.  However, I cant get it to automatically save to excell (the write to spread sheet function doesnt work as "The type of the source is 1-D array of cluster of 5 elements."
    It would probably be bettter if i could use the output of the vision assistant (shape detection) straight away without having to save to excell but I cannot extract the information i need from the output as none of the array/cluster functions seem compatible with the data.  I am using labview 10 and have attached my VI below any help would be greatly appreciated!
    Attachments:
    image to coords (good).vi ‏109 KB

    Hello hzub1,
    It seems your having trouble getting to the information in the output of your Vision Assistant. You can use Context Help (Ctrl+H to show) to help understand the contents of a large array or cluster when you hover your mouse over the wire (see below).
    Looking at the above I created the code below which breaks out all the contents of one item in the array.
    Here I use the Index Array function to break out one element of the array. Each element is a circle descriptor, cluster of 5 elements so I use the Unbundle by Name function to access each of the values in the cluster
    I hope this helps,
    Jack. W
    Applications Engineer
    National Instruments

  • How to get max and min salary in a table

    How to get max and min salary in a table

    SQL> select max(sal),min(sal) from emp;
      MAX(SAL)   MIN(SAL)
          5512        800
    SQL>

  • In mdx how to get max date for all employees is it posible shall we use group by in mdx

    in mdx how to get max date for all employees is it posible shall we use group by in mdx
    example
    empno  ename date
    1         hari        12-01-1982
    1         hari        13-06-2000
    by using above data i want to get max data

    Hi Hari3109,
    According to your description, you want to get the max date for the employees, right?
    In your scenario, do you want to get the max date for all the employees or for each employee? In MDX, we have the Max function to achieve your requirement. You can refer to Naveen's link or the link below to see the details.
    http://www.sqldbpros.com/2013/08/get-the-max-date-from-a-cube-using-mdx/
    If this is not what you want, please provide us more information about the structure of you cube, so that we can make further analysis.
    Regards,
    Charlie Liao
    TechNet Community Support

  • How to get second maximum salary from employee table(sql query)

    how to get second maximum salary from employee table(sql query)

    dude there is no matter of structure .........that user already said its from employee table ...............its basic table in sql and there is no need to specify the table structure
    .........i think u got my point I think you are the one who didn't understand Sarma's point.
    Give a man a fish and you feed him once. Teach a man how to fish and you feed him a life long.
    >
    and the query is
    select max(sal) from emp where sal<(select max(sal)
    from emp);
    this will give the 2nd max salary from the emp tableBtw: You solution is bad, because it needs to scan and sort the table emp twice. And a better solution has been given already.
    Message was edited by:
    Sven W. - reordered statements

  • Getting the background color from a row

    I'm displaying a table that has alternating row colors for odd and even... when I click on a row I am changing the color to blue. When I click on a different row I want to set the background color back to what it was for the originally selected row and change the currently selected row to blue. This worked just fine when I had the colors hard coded into the code... but as soon as I started using style sheets it stoped working,
    My questions is how do I get the background color from a row... for instance, the following alert dislays nothing. How can I get the actual color out for the row?
    var tableElem = document.getElementById('table');
    var rowElem;
    rowElem = tableElem.rows[0];
    alert(rowElem.bgColor);
              

    If you're working with style sheets, then ignore the background color. You don't want to care what color is actully being used, only that the correct style is in place.
    Worry instead about the className property for your row:<style>
    .highlightRow {
       color: white;
       background-color: gray;
    .normalRow {
       color: black;
       background-color: white;
    </style>
    var tableElem = document.getElementById("table");
    var rowElem = tableElem.rows[0];
    alert(rowElem.className);
    <table id="table">
    <tr class="normalRow"><td>...</td></tr>
    <tr class="highlightRow"><td>...</td></tr>
    </table>

  • How to get all the values from the dropdown menu

    How to get all the values from the dropdown menu
    I need to be able to extract all values from the dropdown menu; I know how to get all those values as a string, but I need to be able to access each item; (the value in a dropdown menu will change dynamically)
    How do I get number of item is selection dropdown?
    How do I extract a ?name? for each value, one by one?
    How do I change a selection by referring to particular index of the item in a dropdown menu?
    Here is the Path to dropdown menu that I'm trying to access (form contains number of similar dropdowns)
    RSWApp.om.GetElementByPath "window(index=0).form(id=""aspnetForm"" | action=""advancedsearch.aspx"" | index=0).formelement[SELECT](name=""ctl00$MainContent$hardwareBrand"" | id=""ctl00_MainContent_hardwareBrand"" | index=16)", element
    Message was edited by: testtest

    The findElement method allows various attributes to be used to search. Take the following two examples for the element below:
    <Select Name=ProdType ID=testProd>
    </Select>
    I can find the element based on its name or any other attribute, I just need to specify what I am looking for. To find it by name I would do the following:
    Set x = RSWApp.om.FindElement("ProdType","SELECT","Name")
    If I want to search by id I could do the following:
    Set x = RSWApp.om.FindElement("testProd","SELECT","ID")
    Usually you will use whatever is available. Since the select element has no name or ID on the Empirix home page, I used the onChange attribute. You can use any attribute as long as you specify which one you are using (last argument in these examples)
    You can use the FindElement to grab links, text boxes, etc.
    The next example grabs from a link on a page
    Home
    Set x = RSWApp.om.FindElement("Home","A","innerText")
    I hope this helps clear it up.

  • How to get the return values from a web page

    Hi all :
       how to get the return values from a web page ?  I mean how pass values betwen webflow and web page ?
    thank you very much
    Edited by: jingying Sony on Apr 15, 2010 6:15 AM
    Edited by: jingying Sony on Apr 15, 2010 6:18 AM

    Hi,
    What kind of web page do you have? Do you have possibility to for example make RFCs? Then you could trigger events (with parameters that could "return" the values) and the workflow could react to those events. For example your task can have terminating events.
    Regards,
    Karri

  • How to get warranty service claim from nokia c5-03...

    how to get warranty service claim from nokia c5-03 in india because i have problem with nokia c5-03 I Purchase 2 week ago a new nokia c5-03 but from day 1 i facing same problem like 1) app close itself 2) internet browse close if any thing is downloading or downloading over 3) memory full always then i should reboot the phone then it work. 4) ovi map is open it shows memory full close the app So kindly help me how to get warranty service claim from nokia c5-03 in india i am unhappy with nokia c5-03
    Solved!
    Go to Solution.

    i updated software also but the same problem cont... I want to know that nokia will give back money or exchange for other new mobile

  • For some reason the system is telling me my birth date is wrong when it's not and it won't let me proceed to reset my password. Can someone tell me how to get a "real" person from tech on line?

    For some reason the system is telling me my birth date is wrong when it's not and it won't let me proceed to reset my password. Can someone tell me how to get a "real" person from tech on line?

    contact itunes support

  • How to get the current week from sysdate?

    Hi sir,
    i want to know how to get the current week from sysdate?
    thanks

    Hi Nicolas
    It seems you like to check my post and also make commend ;) thanks for your attention
    Have you ever read the posts above and given solutions ?Yes, I did
    Have you read the docs ? Yes, I checked
    What's the added value here ?Did youYou shared doc with solution(long one), I shared short one which point same solution(Check what Joel posted)..So what is benefit, As you can guess oracle docs are sometimes become so complicated as specialy for beginner...(At least it was like that for me and Belive me somedocs are still sooo complicated even for oracle coworkers ) But for you I dont know ;)
    => Why writting the PS in bold ?Why.. Let me think... Ohh Maybe I am looking some questions(many) and even user get answer they should not changed status so I am reading some posts and try to get problem and loosing time..
    So I am putting that PS wiht BOLD because I dont wanna lose time my friend ;) Because While I am trying to help ppl here In same time I am trying to giving support to my customer prod systems. Which mean time is very important for me...
    Hope my answer could satisfy you..
    One important PS for you.. You may not like my posts (or someone) but my friend I become tired to read&answer and make commend to on your comment which is about my posts.
    I am not newbie in forum(At least I fell like that) and I belive I know how I should make post..
    Thank you
    Regards
    Helios

  • How to get the selection parameters from logical database into one of the t

    Hi Sap ABAP Champians,
    How to get the selection parameters from logical database into one of the tab in the tabstrip selection-screen.
    Please help me for this
    Thanks
    Basu

    Hi
    Thanks, that will work, but then I'll have to insert code into all my reports.
    I can see that "Application Server Control Console" is able to rerun a report.
    This must mean that the Report Server has access to the runtime parameters.
    But how?
    Cheers
    Nils Peter

  • How to get the reverse color of a color

    how to get the reverse color of a color
    thanks

    int red = Math.abs(255 - oldColor.getRed());
    int green = Math.abs(255 - oldColor.getGreen());
    int blue = Math.abs(255 - oldColor.getBlue());
    java.awt.Color inverseColor = new java.awt.Color(red, green, blue);
    Where oldColor is a java.awt.Color object.
    Hope this is want u need !!!

  • How to get payment document number from paid column in monthly invoice

    Dear experts
    I use SBO japan version and i need to know how to get payment document number from paid column in monthly invoice ?
    in table MIN1, only contain invoice and credit note document number, there is no payment document number
    thank you for your help
    Best Regards
    JeiMing

    Dear Gordon
    Yeah, you are right, i can use field MIentry in RCT2
    thank you
    Best regards
    jeiming

Maybe you are looking for

  • Can the new devices play nice with each other?

    I am considering getting and Apple TV and the new wireless base station. My question is this: Can I use the wireless base station and connect a 250gb LaCie HD to it for media storage and back up and then have Apple TV connect to that hard drive to ge

  • FAGL_FC_VAL executed but the batch is not processed in SM35

    Hi, FAGL_FC_VAL executed but the batch is not processed in SM35 and I deleted this batch (Session). My understanding is when we execute FAGL_FC_VAL only system valuate but posting happens only when we run the session in SM35. Am I correct ? Or have I

  • Dynamically Labeling a pie chart (arc2d_pie)

    Can Somebody guide me how to Dynamically labling a pie chart inside or outside of it.Atpresent I am using rectangle color-code for labling at the top and left side of arch2d but its very confusing as the pie segments grows in number .I am submitting

  • Data Modeling In JDeveloper

    How good is JDeveloper at data modeling (ER Diagrams)?

  • GIS - Realize Drill Down with the Web Item "Map" (WAD)

    Hi experts, can somebodye tell me how to realize a drill down (on mouse click) on the web item map (Web Application Designer) ? To drill down in a map from a country to a region for example. I need the function "filter and change drill down" on mouse