Convert dominant color with selected color - javascript

After working/studying hours with canvas i have managed to get the image clone and it's pixels now i have made the user select a color from a color specterm and i have that color hex in my function :
move: function (color) {
// 'color' is the value user selected
var img_id = jQuery(".selected_bg_img").attr("id");
alert(img_id);
var x = 0;
var y = 0;
var width = 409;
var height = 409;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById(img_id);
ctx.drawImage(img,x,y,width,height);
var imageData = ctx.getImageData(0,0,width,height);
var data = imageData.data;
alert(data);
}
now two tasks are getting in way,
1. How do we extract the maximum color from data ?
2. How do we convert that maximum color to the color we got in function ?
for live working example i have link given at end
NOTE: Select the images (any last 3) from left side of the product image and and when color is choose it clones the image to the canvas below.
Here i am trying to clone the image with replacement of maximum color with the color user selected.
NOTE: Maximum color i mean (dominant color in image), e.g http://lokeshdhakar.com/projects/color-thief/ this project is getting the dominant color of image but it's on node and i'm trying to get the dominant and to change that color before cloning too .
for (var i=0;i<imgData.data.length;i+=4)
{
imgData.data[i]=255-imgData.data[i];
imgData.data[i+1]=255-imgData.data[i+1];
imgData.data[i+2]=255-imgData.data[i+2];
imgData.data[i+3]=255;
}
*****EDIT*****
My problem is not very complex i think i have this image
so we can see clearly that the dominant color is grey, by any method i am just trying to replace that color with the new color i have in my function move and draw that image with the new color. The image from where i have taken and shows another example :
http://www.art.com/products/p14499522-sa-i3061806/pela-silverman-colorful-season-i.htm?sOrig=CAT&sOrigID=0&dimVals=729271&ui=573414C032AA44A693A641C8164EB595
on left side of image when we select the similar image they have option "change color" at the bottom center of image. This is what exactly i'm trying to do.
So now i tried to read the image 1x1 and this is what i get in the console when i log it(particular for the image i have shown) :
[166, 158, 152, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…]
So it maybe the very first start from top left corner, i guess it need to be iterated over whole image and this is what i get when i iterated over whole image:
[110, 118, 124, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255…]
The loop i used for iteration is:
var imageData = ctx.getImageData(0,0,width,height);
var data = imageData.data;
for (var i=0;i<data.length;i+=4)
{
data[i]=255-data[i];
data[i+1]=255-data[i+1];
data[i+2]=255-data[i+2];
data[i+3]=255;
}
console.log(data);
Is this iteration right ? If yes, it seems to be now matter of replacing the dominant color and i'm blank here how do we replace it and write back image with the replaced color or is there something more ?
*************EDIT***********
i have now user value in rgb, need to look for places where that value should be placed

This answer may be what you want as it is a little unclear.
Finding the dominant colour in an image
There are two ways that I use. There are many other ways to do it, which is the best is dependent on the needs and quality requiered. I will concentrat on using a histogram to filter out irrelevent pixels to get a result.
The easy way.
Create a canvas that is 1 by 1 pixel. Ensure that canvas smoothing is on.
ctx.imageSmoothingEnabled = true;
ctx.mozImageSmoothingEnabled = true;
The draw the image onto that 1 by 1 canvas
ctx.drawImage(image,0,0,1,1);
Get the pixel data
var data = ctx.getImageData(0,0,1,1);
And the rgb values are what you are after.
r = data.data[0];
g = data.data[0];
b = data.data[0];
The result applied to the image below.
The long way
This method is long and problematic. You need to ignore the low and high values in the histogram for rgb (ignore black and white values) and for HSL ignore Saturations and Values (Lightness) that are 0 or 100% or you will get reds always dominating for images that have good contrast.
In image processing a histogram is a plot of the distribution of image properties (eg red green blue) within the image. As digital images have discrete values the histogram (a bar graph) will plot along the x axis the value and in the y axis the number of pixels that have that value.
An example of the histogram. Note that this code will not run here as there is cross origin restriction. (sorry forgot my browser had that disabled).
/** CopyImage.js begin **/
// copies an image adding the 2d context
function copyImage(img){
var image = document.createElement("canvas");
image.width = img.width;
image.height = img.height;
image.ctx = image.getContext("2d");
image.ctx.drawImage(img, 0, 0);
return image;
}
function copyImageScale(img,scale){
var image = document.createElement("canvas");
image.width = Math.floor(img.width * scale);
image.height = Math.floor(img.height * scale);
image.ctx = image.getContext("2d");
image.ctx.drawImage(img, 0, 0,image.width,image.height);
return image;
}
/** CopyImage.js end **/
function getHistogram(img){ // create a histogram of rgb and Black and White
var R,G,B,BW;
R = [];
G = [];
B = [];
BW = []; // Black and white is just a mean of RGB
for(var i=0; i < 256; i++){
R[i] = 0;
G[i] = 0;
B[i] = 0;
BW[i] = 0;
}
var max = 0; // to normalise the values need max
var maxBW = 0; // Black and White will have much higher values so normalise seperatly
var data = img.ctx.getImageData(0,0,img.width,img.height);
var d = data.data;
var r,g,b;
i = 0;
while(i < d.length){
r = d[i++]; // get pixel rgb values
g = d[i++];
b = d[i++];
i++; // skip alpha
R[r] += 1; // count each value
G[g] += 1;
B[b] += 1;
BW[Math.floor((r+g+b)/3)] += 1;
}
// get max
for(i = 0; i < 256; i++){
max = Math.max(R[i],G[i],B[i],max);
maxBW = Math.max(BW[i],maxBW);
}
// return the data
return {
red : R,
green : G,
blue : B,
gray : BW,
rgbMax : max,
grayMax : maxBW,
};
}
function plotHistogram(data,ctx,sel){
var w = ctx.canvas.width;
var h = ctx.canvas.height;
ctx.clearRect(0,0,w,h); // clear any existing data
var d = data[sel];
if(sel !== "gray"){
ctx.fillStyle = sel;
}
var rw = 1 / d.length; // normalise bar width
rw *= w; // scale to draw area;
for(var i = 0; i < d.length; i++ ){
var v = 1-(d[i]/data.rgbMax); // normalise and invert for plot
v *= h; // scale to draw area;
var x = i/d.length; // normaise x axis
x *= w; // scale to draw area
if(sel === 'gray'){
ctx.fillStyle = "rgb("+i+","+i+","+i+")";
}
ctx.fillRect(x,v,rw,h-v); // plot the bar
}
}
var canMain = document.createElement("canvas");
canMain.width = 512;
canMain.height = 512;
canMain.ctx = canMain.getContext("2d");
document.body.appendChild(canMain);
var ctx = canMain.ctx;
var can = document.createElement("canvas");
can.width = 512;
can.height = 512;
can.ctx = can.getContext("2d");
// load image and display histogram
var image = new Image();
image.src = "http://i.stack.imgur.com/tjTTJ.jpg";
image.onload = function(){
image = copyImage(this);
var hist = getHistogram(image);
// make background black
ctx.fillStyle = "black"
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
// create and show each plot
plotHistogram(hist,can.ctx,"red");
document.body.appendChild(copyImageScale(can,0.5));
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"green");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "lighter"
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"blue");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "lighter"
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"gray");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "source-over"
ctx.globalAlpha = 0.9;
ctx.drawImage(can,0,0,canvas.width,canvas.height);
ctx.globalAlpha = 1;
}
As the above code required a hosted image the results are shown below.
The image
The RGB and gray histograms as output from above code.
From this you can see the dominant channels and the distribution of rgb over the image (Please note that I removed the black as this image has a lot of black pixels that where make the rest of the pixel counts shrink into insignificance)
To find the dominant colour you can do the same but for the HSL values. For this you will need to convert from RGB to HSL. This answer has a function to do that. Then it is just a matter of counting each HSL value and creating a histogram.
The next image is a histogram in HSL of the above sample image.
As you can see there is a lot of red, then a peek at yellow, and another in green.
But as is this still will not get you what you want. The second histogram (saturation) shows a clear peak in the center. There are a lot of colours that have good saturation but this does not tell you what colour that is.
You need to filter the HSL value to around that peak.
What I do is multiply the HSL values by the f(s) = 1-Math.abs(s-50)/50 s is Saturation range 0-100. This will amplify hue and value where saturation is max. The resulting histogram looks like
Now the peak hue (ignoring the reds) is orange. The hue value is ~ 42. Then you apply a filter that removes all pixels that are not near the hue = 42 (you may want to give a falloff). You apply this filter on the HSL value you get after the last step. The next image shows the resulting image after applying this filter to the original
and then get a sum of all the remaining pixel's R,G,B. The mean of each RGB value is the common colour.
The common colour as by this method.
Note the result is different than if you apply this method as described and in the code above. I used my own image processing app to get the instrume steps and it uses true logarithmic photon counts for RGB values that will tend to be darker than linear interpolation. The final step expands the filtered pixel image to an instrume step that is too complicated to describe here (a modification on the easy method at start of answer). looks like
Also I applied this to the whole image, this can be very slow for large images, but it will work just as well if you first reduce the size of the image (must have image smoothing on (defaults of most browsers)). 128 8 128 is a good size but you can go down lower. It will depend on the image how small you can make it befor it fails.

Related

Is there a faster way to render the Mandelbrot set for an animation?

I'm trying to code the Mandelbrot set as a fun project. I did it on my own, so it probably isn't optimized very well. I have a few questions about how to make my code better and how to add certain things to it. I used the library p5js, but that probably doesn't matter. (My code is at the bottom.)
First of all, when I render the set, the edges are very sharp. For example: See how the edges are sharp, because it operates pixel by pixel. However, I see in, for example, the Wikipedia page that it is possible to blend pixels and give more detail to the picture. How might I go about doing this? I've thought about calculating four values for each pixel, and blending them, but I feel like there should be another way.
Secondly, rendering the set takes much longer than it can if I want to animate it. I have to iterate more and more the more I zoom, so each frame would end up taking entire minutes to render. However, then I see videos like this https://www.youtube.com/watch?v=LhOSM6uCWxk or this https://www.youtube.com/watch?v=b005iHf8Z3g and I'd like to know how they are able to render these in less than a century. Is there an optimization method that I'm missing out on?
Another thing about the videos is how they are colored. For example, the first video I showed seemed like the colors were moving around everywhere, instead of staying in a constant spot, like the second video. What is the coloring method?
I've tried making the iterations low, but then I lose quality. I've tried an array of colors, but then it looks flat, like the second video. I want to know what's going on that I'm missing. I've looked at other solutions and seen that some people are rendering one pixel at a time, and that's what is making it slow. I do rows at a time for speed. All in all, what should I change to animate a set that looks pretty cool?
Finally, is there anything else that I should know to make my Mandelbrot set look amazing? Is there a completely different method for rendering that I should know? How is the first video made to look 3D? All of these clarifications would be nice to know.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/addons/p5.sound.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<main>
</main>
<script src="sketch.js"></script>
</body>
</html>
//noprotect
var y = 0;
var ratio;
var xstart = -2;
var xend = 2;
var ystart = -2;
var yend = 2;
var maxiter = 100;
var _xstart;
var _xend;
const colors = [
"rgb(255, 0, 255)",
"rgb(255, 0, 127)",
"rgb(255, 0, 0)",
"rgb(255, 127, 0)",
"rgb(255, 255, 0)",
"rgb(127, 255, 0)",
"rgb(0, 255, 0)",
"rgb(0, 255, 127)",
"rgb(0, 255, 255)",
"rgb(0, 127, 255)",
"rgb(0, 0, 255)",
"rgb(127, 0, 255)"
];
function setup() {
noStroke();
createCanvas(window.innerWidth, window.innerHeight);
ratio = width/height;
background(0);
_xstart = xstart * (width/height);
_xend = xend * (width/height);
_xstart = (xstart + xend)/2 + xstart*(width/height);
_xend = (xstart+xend)/2 + xend*(width/height);
}
function mandelbrot(rconst, iconst) {
var iter = math.complex(0, 0);
var current = 0;
for(var i = 0; i < maxiter; i ++) {
iter = iter.pow(2);
iter = iter.add(rconst, iconst);
current ++;
if(sqrt(pow(iter.re, 2)+pow(iter.im, 2)) > 2) {
break;
}
}
if(current === maxiter) {
return(0);
} else {
//color array
return(colors[(current) % colors.length]);
//purple
var temp = floor(map(current, 0, maxiter/3, 0, 255));
if(temp > 255) {
temp = 255;
}
// return('rgb(' + temp + ', 0, ' + temp + ')')
//black and white
// return(map(current, 0, 30, 0, 255))
return('rgb(0, 0, ' + temp + ')')
}
}
function draw() {
if(y < height+1) {
for(var x = 0; x < width+1; x ++) {
fill(mandelbrot(map(x, 0, width, _xstart, _xend), map(y, 0, height, ystart, yend)))
rect(x, y, 1, 1);
}
y++;
}
fill(0);
rect(0, 0, 300, 15);
fill(255);
text("x: " + map(mouseX, 0, width, _xstart, _xend) + ", y: " + map(mouseY, 0, height, ystart, yend), 0, 10);
}

Is there a way to generate a random contrast level on html canvas?

I am trying to present this shape as a stimulus in a behavioral experiment. I wantthe image to have a random contrast level between 0 and 1. I am trying to use Math.random() for that but when I run this in Chrome the shape flickers when it is presented on the screen. Is there a way to present a stable shape with randomly generated contrast levels?
drawFunc: function gabor() {
context = jsPsych.currentTrial().context;
context.beginPath();
const gradLength = 100;
const my_gradient = context.createLinearGradient(850, 0, 1050, 0);
my_gradient.addColorStop(0,'rgb(0, 0, 0)');
my_gradient.addColorStop(0.05,'rgb(255, 255, 255)');
my_gradient.addColorStop(0.1,'rgb(0, 0, 0)');
my_gradient.addColorStop(0.15,'rgb(255, 255, 255)');
my_gradient.addColorStop(0.2,'rgb(0, 0, 0)');
my_gradient.addColorStop(0.25,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.3,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.35,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.4,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.45,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.5,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.55,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.6,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.65,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.7,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.75,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.8,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.85,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.9,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.95,"rgb(255, 255, 255)");
my_gradient.addColorStop(1,"rgb(0, 0, 0)");
var result1 = Math.random();
context.filter = 'contrast('+ result1 +')';
context.fillStyle=my_gradient;
context.fillRect(950,300,gradLength,gradLength);
context.stroke();
Use a setup function to get the constants
Create the gradient once
Get the context once.
Create contrast once using a function. See example
Remove setup code from draw function.
Remove random contrast value from draw function.
Remove redundant code
No need for context.beginPath(); as you draw the using fillRect
No need for context.stroke(). Not sure why you are calling stroke as you have not defined a path after the beginPath call
Why assign a named function gabor to object property drawFunc Do you call the function using its name or the property. Which ever you use makes the other redundent.
Example
setup() {
this.ctx = jsPsych.currentTrial().context;
const g = this.gradient = this.ctx.createLinearGradient(850, 0, 1050, 0);
const bands = 10, colors = ["#000", "#FFF"];
const stops = bands * colors.length;
var pos = 0;
while (pos <= stops) {
g.addColorStop(pos / stops, colors[pos % colors.length]);
pos++;
}
},
randomContrast() {
this.contrast = Math.Random();
this.drawFunc();
},
drawFunc() {
const ctx = this.ctx;
ctx.filter = 'contrast('+ this.contrast +')';
ctx.fillStyle = this.gradient;
ctx.fillRect(950, 300, 100, 100);
},
Call setup once, then call randomContrast to change the contrast. If you need to redraw the gradient without changing the contrast call drawFunc

How can we set different `colors` for different objects detected using YOLO

How can we set different colors for different objects detected using YOLO. Now everything detected are displaying in green rectangle.
function draw() {
image(video, 0, 0, width, height); // Displaying image on a canvas
for (let i = 0; i < objects.length; i++) //Iterating through all objects
{
noStroke();
fill(0, 255, 0); //Color of text
text(objects[i].label, objects[i].x * width, objects[i].y * height - 5);
//Displaying the label
noFill();
strokeWeight(4);
stroke(0, 255, 0); //Defining stroke for rectangular outline
rect(objects[i].x * width, objects[i].y * height, objects[i].w * width,
objects[i].h * height);
}
}
stroke() sets a global state, it sets the color used to draw lines and borders around shapes. This state is kept even beyond frames.
This means all objects which are drawn after the call stroke() are drawn with the set color.
If you want to change the color, you've to call stroke() again.
If you want to use different colors the you can define a list of colors and use the modulo operator (%) to get an index of the color list. e.g. use a red, green and blue color:
colorList = [[255, 0, 0], [0, 255, 0], [0, 0, 255]];
function draw() {
// [...]
for (let i = 0; i < objects.length; i++) {
// [...]
let colorI = i % colorList.length;
stroke(...colorList[colorI]);
// [...]
}
}

Turn floating point number into a valid Alpha value for an RGBA CSS colour

I am attempting to fill a Canvas element with a single linear gradient between White and a Dynamic colour that will be determined at runtime.
To this effect, I have this function, that receives a floating point number as it's argument, and I am attempting to plug that variable into the alpha value of a RGBA colour.
function setCanvas(fraction) {
fraction = fraction.toFixed(2);
context.rect(0, 0, canvas.width, canvas.height);
var grad = context.createLinearGradient(0, 0, canvas.width, canvas.height);
grad.addColorStop(0, '#FFFFFF');
grad.addColorStop(1, 'rgba(255, 255, 255, fraction)'); // SYNTAX ERROR
context.fillStyle = grad;
context.fill();
}
This is the error message in the log:
Uncaught SyntaxError: Failed to execute 'addColorStop' on 'CanvasGradient': The value provided ('rgba(255, 255, 255, fraction)') could not be parsed as a color.
I can log the value of fraction and it is always normalized between 0.0 and 1.0, which is what the documentation says it needs... but if I statically type in the same value (0.76, for example) into my RGBA colour, then everything works swimmingly...
Am I missing something obvious? Why isn't this working ?
I think you meant to do this
grad.addColorStop(1, 'rgba(255, 255, 255, ' + fraction+ ')');
You're including the string fraction instead of the value.

Convert a byte array to image data without canvas

Is it somehow possible to convert an byte array to image data without using canvas?
I use currently something like this, however I think that can be done without canvas, or am I wrong?
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");
var byteArray = [
255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, // red
0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, // green
0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255 // blue
];
var imageData = ctx.getImageData(0, 0, 10, 3);
for(var i = 0; i < byteArray.length; i+=4){
imageData.data[i] = byteArray[i];
imageData.data[i+1] = byteArray[i + 1];
imageData.data[i+2] = byteArray[i + 2];
imageData.data[i+3] = byteArray[i + 3];
}
ctx.putImageData(imageData, 0, 0);
http://jsfiddle.net/ARTsinn/swnqS/
Update
I've already tried to convert it into an base64-uri but no success:
'data:image/png;base64,' + btoa(String.fromCharCode.apply(this, byteArray));
Update 2
To split the question from the problem
The canvas itself is it not, rather the fact that
oldIE (and else) don't support it. ...And libraries like excanvas or
flashcanvas seems a bit too bloated for this use case...
canvas.getImageData returns an ImageData object that looks like this:
interface ImageData {
readonly attribute unsigned long width;
readonly attribute unsigned long height;
readonly attribute Uint8ClampedArray data;
};
(See the specs: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#imagedata)
I guess you could box your data fitting that interface and try it out.
If you try, let me know how it turns out :)
Alternatively, you could create an in-memory canvas of your desired width/height--document.createElement("canvas"), Then grab its imagedata and plug in your own array. I know this works. Yes...that goes contrary to your question, but you're not adding the canvas to your page.
Is there a reason you don't want to use canvas? This really is what canvas is for. Once you have the image data what would you do with it? Render it in the browser? Send to a server? Download to the user? If the problem is just that you don't want to have a canvas on screen you could create a hidden canvas to do the work.

Categories

Resources