Get an image's histogram
@return {object} An object with an array of color occurrence counts for each channel (r,g,b)
555128
function histogram() {
  const histogram = {
    r: new Array(256).fill(0),
    g: new Array(256).fill(0),
    b: new Array(256).fill(0)
  };

  this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
    x,
    y,
    index
  ) {
    histogram.r[this.bitmap.data[index + 0]]++;
    histogram.g[this.bitmap.data[index + 1]]++;
    histogram.b[this.bitmap.data[index + 2]]++;
  });

  return histogram;
}
351830
function (idx) {
		var r = this.getRed(idx),
			g = this.getGreen(idx),
			b = this.getBlue(idx);

		r = Math.floor((0.393 * r) + (0.769 * g) + (0.189 * b));
		g = Math.floor((0.349 * r) + (0.686 * g) + (0.168 * b));
		b = Math.floor((0.272 * r) + (0.534 * g) + (0.131 * b));

		r = r < 0 ? 0 : (r > 255 ? 255 : r);
		g = g < 0 ? 0 : (g > 255 ? 255 : g);
		b = b < 0 ? 0 : (b > 255 ? 255 : b);

		return {red: r, green: g, blue: b};
	}
1019477
def get_histograms(params)
      raise ArgumentError unless params[:categoryId]
      response = get_json_response(build_request_url('getHistograms', params))
      response.trim(:getHistorgramsResponse)
      return response
    end
1013149
function createRGBPixelsFromImage(name) {
    
    var rgbPixels = new Promise(function(success, failure) {
    
        try {
            getPixels(name, function(err, pixels) {
                
                if(err) {
                    failure(err);
                } else {
                    success(pixels);
                }
                
            });
        } catch (e) {
            failure(e);
        }

    });

    return rgbPixels;

}
1295107
function() {
  var num_classes = net.layers[net.layers.length-1].out_depth;

  document.getElementById('testset_acc').innerHTML = '';
  var num_total = 0;
  var num_correct = 0;

  // grab a random test image
  for(num=0;num<4;num++) {
    var sample = sample_test_instance();
    var y = sample.label;  // ground truth label

    // forward prop it through the network
    var aavg = new convnetjs.Vol(1,1,num_classes,0.0);
    // ensures we always have a list, regardless if above returns single item or list
    var xs = [].concat(sample.x);
    var n = xs.length;
    for(var i=0;i<n;i++) {
      var a = net.forward(xs[i]);
      aavg.addFrom(a);
    }
    var preds = [];
    for(var k=0;k<aavg.w.length;k++) { preds.push({k:k,p:aavg.w[k]}); }
    preds.sort(function(a,b){return a.p<b.p ? 1:-1;});
    
    var correct = preds[0].k===y;
    if(correct) num_correct++;
    num_total++;

    var div = document.createElement('div');
    div.className = 'testdiv';

    // draw the image into a canvas
    draw_activations_COLOR(div, xs[0], 2); // draw Vol into canv

    // add predictions
    var probsdiv = document.createElement('div');
    
    var t = '';
    for(var k=0;k<3;k++) {
      var col = preds[k].k===y ? 'rgb(85,187,85)' : 'rgb(187,85,85)';
      t += '<div class=\"pp\" style=\"width:' + Math.floor(preds[k].p/n*100) + 'px; background-color:' + col + ';\">' + classes_txt[preds[k].k] + '</div>'
    }
    probsdiv.innerHTML = t;
    probsdiv.className = 'probsdiv';
    div.appendChild(probsdiv);

    // add it into DOM
    $(div).prependTo($("#testset_vis")).hide().fadeIn('slow').slideDown('slow');
    if($(".probsdiv").length>200) {
      $("#testset_vis > .probsdiv").last().remove(); // pop to keep upper bound of shown items
    }
  }
  testAccWindow.add(num_correct/num_total);
  $("#testset_acc").text('test accuracy based on last 200 test images: ' + testAccWindow.get_average());  
}
40253
function() {
        var r = this.rgba[0] / 255, g = this.rgba[1] / 255, b = this.rgba[2] / 255;
        r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
        g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
        b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
        return 0.2126 * r + 0.7152 * g + 0.0722 * b;
    }
1255885
def imageToColor(url: str, scale=200, mode='rgb'):
        """"""
        from PIL import Image
        import colorsys
        if url:
            response = urllib.request.urlopen(url)
            img_buffer = io.BytesIO(response.read())
            img = Image.open(img_buffer)
            img = img.convert('RGBA')
            img.thumbnail((scale, scale))
            statistics = {'r': 0, 'g': 0, 'b': 0, 'coef': 0}
            for cnt, (r, g, b, a) in img.getcolors(img.size[0] * img.size[1]):
                hsv = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
                saturation = hsv[1] * 255
                coefficient = (saturation * cnt * a) + 0.01  # avoid 0
                statistics['r'] += coefficient * r
                statistics['g'] += coefficient * g
                statistics['b'] += coefficient * b
                statistics['coef'] += coefficient
                color = (
                    int(statistics['r'] / statistics['coef']),
                    int(statistics['g'] / statistics['coef']),
                    int(statistics['b'] / statistics['coef'])
                )
            if mode.lower() == 'rgb':
                return color
            elif mode.lower() == 'hex':
                return "#%0.2X%0.2X%0.2X" % color
            else:
                return color
        else:
            return False
230286
function getRGBBytes(color, out) {
    out = out || [0, 0, 0];
    out[0] = Math.round(color[0]*255);
    out[1] = Math.round(color[1]*255);
    out[2] = Math.round(color[2]*255);
    return out;
}
767383
public Histogram histogram(double[] data, int k, Color color) {
        return histogram(null, data, k, color);
    }
1238135
function getImageData(diagram, type) {
    // Make a new canvas element for making image data
    var canvasElement = new Canvas(500, 500, type),
        canvas        = new mdjson.Graphics.Canvas(canvasElement.getContext("2d")),
        boundingBox   = diagram.getBoundingBox(canvas),
        rectExpand    = 10;

    // Initialize new canvas
    boundingBox.expand(rectExpand);
    canvas.origin = new mdjson.Graphics.Point(-boundingBox.x1, -boundingBox.y1);
    canvas.zoomFactor = new mdjson.Graphics.ZoomFactor(1, 1);
    canvasElement.width = boundingBox.getWidth();
    canvasElement.height = boundingBox.getHeight();

    // Draw diagram to the new canvas
    diagram.drawDiagram(canvas);
    return canvasElement.toBuffer();
}
906493
function flipHistogram(histo2d) {
  const newHisto2d = {
    bins: histo2d.bins.map((bin) => {
      const { x, y, count } = bin;
      return {
        x: y,
        y: x,
        count,
      };
    }),
    x: histo2d.y,
    y: histo2d.x,
    maxCount: histo2d.maxCount,
    numberOfBins: histo2d.numberOfBins,
  };

  return newHisto2d;
}
1259620
function getHistogram(domain, mappedValue) {
  const histogram = histogramConstruct(domain, mappedValue, histogramBins);
  const enlargedHistogram = histogramConstruct(
    domain,
    mappedValue,
    enlargedHistogramBins
  );

  return {histogram, enlargedHistogram};
}
882462
function (colour) {
  if (!colour || !!((colour = String(colour)).indexOf("-") + 1)) {
    return {r: -1, g: -1, b: -1, opacity: -1, error: 1};
  }
  if (colour == "none") {
    return {r: -1, g: -1, b: -1, opacity: -1};
  }
  !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
  if (!colour) {
    return {r: -1, g: -1, b: -1, opacity: -1, error: 1};
  }
  var res,
      red,
      green,
      blue,
      opacity,
      t,
      values,
      rgb = colour.match(colourRegExp);
  if (rgb) {
    if (rgb[2]) {
      blue = parseInt(rgb[2].substring(5), 16);
      green = parseInt(rgb[2].substring(3, 5), 16);
      red = parseInt(rgb[2].substring(1, 3), 16);
    }
    if (rgb[3]) {
      blue = parseInt((t = rgb[3].charAt(3)) + t, 16);
      green = parseInt((t = rgb[3].charAt(2)) + t, 16);
      red = parseInt((t = rgb[3].charAt(1)) + t, 16);
    }
    if (rgb[4]) {
      values = rgb[4].split(commaSpaces);
      red = parseFloat(values[0]);
      values[0].slice(-1) == "%" && (red *= 2.55);
      green = parseFloat(values[1]);
      values[1].slice(-1) == "%" && (green *= 2.55);
      blue = parseFloat(values[2]);
      values[2].slice(-1) == "%" && (blue *= 2.55);
      rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = parseFloat(values[3]));
      values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
    }
    if (rgb[5]) {
      values = rgb[5].split(commaSpaces);
      red = parseFloat(values[0]);
      values[0].slice(-1) == "%" && (red /= 100);
      green = parseFloat(values[1]);
      values[1].slice(-1) == "%" && (green /= 100);
      blue = parseFloat(values[2]);
      values[2].slice(-1) == "%" && (blue /= 100);
      (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
      rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = parseFloat(values[3]));
      values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
      return hsb2rgb(red, green, blue, opacity);
    }
    if (rgb[6]) {
      values = rgb[6].split(commaSpaces);
      red = parseFloat(values[0]);
      values[0].slice(-1) == "%" && (red /= 100);
      green = parseFloat(values[1]);
      values[1].slice(-1) == "%" && (green /= 100);
      blue = parseFloat(values[2]);
      values[2].slice(-1) == "%" && (blue /= 100);
      (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
      rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = parseFloat(values[3]));
      values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
      return hsl2rgb(red, green, blue, opacity);
    }
    red = Math.min(Math.round(red), 255);
    green = Math.min(Math.round(green), 255);
    blue = Math.min(Math.round(blue), 255);
    opacity = Math.min(Math.max(opacity, 0), 1);
    rgb = {r: red, g: green, b: blue};
    rgb.opacity = isFinite(opacity) ? opacity : 1;
    return rgb;
  }
  return {r: -1, g: -1, b: -1, opacity: -1, error: 1};
}
1088382
function extractHOGFromHistograms(histograms, options) {
  var blockSize = options.blockSize || 2;
  var blockStride = options.blockStride || (blockSize / 2);
  var normalize = norms[options.norm || "L2"];

  var blocks = [];
  var blocksHigh = histograms.length - blockSize + 1;
  var blocksWide = histograms[0].length - blockSize + 1;

  for (var y = 0; y < blocksHigh; y += blockStride) {
    for (var x = 0; x < blocksWide; x += blockStride) {
      var block = getBlock(histograms, x, y, blockSize);
      normalize(block);
      blocks.push(block);
    }
  }
  return Array.prototype.concat.apply([], blocks);
}
1133397
def twoDimensionalHistogram(title, title_x, title_y,
                            z, bins_x, bins_y,
                            lim_x=None, lim_y=None,
                            vmin=None, vmax=None):
    
    plt.figure()

    mesh_x, mesh_y = np.meshgrid(bins_x, bins_y)

    if vmin != None and vmin == vmax:
        plt.pcolor(mesh_x, mesh_y, z)
    else:
        plt.pcolor(mesh_x, mesh_y, z, vmin=vmin, vmax=vmax)
    plt.xlabel(title_x)
    plt.ylabel(title_y)
    plt.title(title)
    plt.colorbar()

    if lim_x:
        plt.xlim(lim_x[0], lim_x[1])
    if lim_y:
        plt.ylim(lim_y[0], lim_y[1])
188753
function getPixelSetter() {
    var offset = 0;
    return function(colors, c) {
        colors[offset] = c.r;
        colors[offset + 1] = c.g;
        colors[offset + 2] = c.b;
        colors[offset + 3] = c.a;
        offset += 4;
    };
}
1262138
function(opt_randFunc) {
    var randFunc = opt_randFunc || randInt;
    var strong = randFunc(3);
    var colors = [];
    for (var ii = 0; ii < 3; ++ii) {
      colors.push(randFunc(128) + (ii === strong ? 128 : 64));
    }
    return "rgb(" + colors.join(",") + ")";
  }