Search code examples
javaif-statementrgbjava-3d

Dividing 3D spacel into same size blocks


I have an array with a list of colors in rgb. What I want to do is to group the colors so that when doing a hash map, I dont have a lot of entries with colors that only appear in one pixel. I have decided to divide the color space into 64 bins of equal size, and assign each color to a bin and then do the count of the hash map for each bin instead of pixel. However, I dont know how to do this is a simple way, my approach is the following:

int r = c.getRed();
int b = c.getBlue();
int g = c.getGreen();
//declare all bins as arrays

if (0 = < r =<63) {
    if (0=< g =< 63) {
        if (0=< b =< 63) {
            bin1= push.c;
        if (64 =<b =<126){
            bin2= push.c;
        if (127 =<b =< 190)
            bin3 =push.c;
        }
        if (191 =<b =< 255)
            bin4 = push.c;
        }
    if (64 =<g =<126){
        if (0=< b =< 63) {
            bin5= push.c;
        if (64 =<b =<126){
            bin6= push.c;
        if (127 =<b =< 190)
            bin7 =push.c;
        }
        if (191 =<b =< 255)
            bin8 = push.c;
        }
    if (127 =<g =<190){
        if (0=< b =< 63) {
            bin9= push.c;
        if (64 =<b =<126){
            bin10= push.c;
        if (127 =<b =< 190)
            bin11 =push.c;
        }
        if (191 =<b =< 255)
            bin12 = push.c;
        }
    if (190 =<g =<255){
        if (0=< b =< 63) {
            bin13= push.c;
        if (64 =<b =<126){
            bin14= push.c;
        if (127 =<b =< 190)
            bin15 =push.c;
        }
        if (191 =<b =< 255)
            bin16 = push.c;
        }  
     ...
    }
}

This process is tedious and not really efficient. But I dont know another way of doing it.


Solution

  • For starters, instead if bin variables called bin1, bin2, etc, make bin an array.

    Then you only need to decide how to set the index of the array - and that's just a bit of maths. For exact colour, you're splitting the range 0..255 into 4 (0..63, 64..127, etc). You get the same effect by dividing by 64 (discarding remainder).

    So, all those 'if' statements could be replaced by :

    int idx = 16 * (r/64) + 4 * (g/64) + (b/64);
    bin[idx] = push.c;