I have the following code that every so often creates a canvas, puts an image of a bulb on it and changes all the yellow pixels to a colour that is passed in. When the colour of the bulb changes you are still able to see all the old canvas objects in the console in safari under the canvas tab. Does this mean they are taking up memory? Should they not disappear when they go out of scope (When the colour changes and a new bulb is used)?
// Set colour of light bulb
function set_bulb_colour(img_id, rgb_colour)
{
// Load the light bulb image in and redraw it with the new colour
var img = new Image();
img.onload = function()
{
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var image_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (var i = 0; i < image_data.data.length; i += 4)
{
// If the pixel is yellow set it to the new colour
if (image_data.data[i + 3] != 0 && (image_data.data[i] > 200 && image_data.data[i + 2] < 100))
{
image_data.data[i] = rgb_colour[0];
image_data.data[i + 1] = rgb_colour[1];
image_data.data[i + 2] = rgb_colour[2];
}
}
ctx.putImageData(image_data, 0, 0);
// Set the image src to the bulb with the new colour
$(img_id).attr('src', canvas.toDataURL());
}
img.src = 'images/light_bulb.png';
}
Here you can see that there are multiple canvas', the purple and red ones have gone and the pink one is now displayed, but the red and purple ones aren't disappearing, are they using up memory? Every time the colour changes a new canvas is added to the queue, I expected the older ones to be removed. Hope I explained that ok.
edit: imd_id is always the same at the minute, so the new image just replaces the old one.
Related
I'm developing an app that has a painting feature. The user can paint on an image that is initially made of only pure black and pure white pixels. Later, after the user has finished painting, I need to do some processing on that image based on the colors of each pixel.
However, I realized that by the time I processed the image, the pixels weren't purely black/white anymore, but there were lots of greys in between, even if the user didn't paint anything. I wrote some code to check it and found out there were over 250 different colors on the image, while I was expecting only two (black and white). I suspect canvas is messing with my colors somehow, but I can't figure out why.
I hosted a demo on GitHub, showcasing the problem.
The image
This is the image. It is visibly made of only black and white pixels, but if you want to check by yourself you can use this website. It's source code is available on GitHub and I used it as a reference for my own color counting implementation.
My code
Here is the code where I load the image and count the unique colors. You can get the full source here.
class AppComponent {
/* ... */
// Rendering the image
ngAfterViewInit() {
this.context = this.canvas.nativeElement.getContext('2d');
const image = new Image();
image.src = 'assets/image.png';
image.onload = () => {
if (!this.context) return;
this.context.globalCompositeOperation = 'source-over';
this.context.drawImage(image, 0, 0, this.width, this.height);
};
}
// Counting unique colors
calculate() {
const imageData = this.context?.getImageData(0, 0, this.width, this.height);
const data = imageData?.data || [];
const uniqueColors = new Set();
for (let i = 0; i < data?.length; i += 4) {
const [red, green, blue, alpha] = data.slice(i, i + 4);
const color = `rgba(${red}, ${green}, ${blue}, ${alpha})`;
uniqueColors.add(color);
}
this.uniqueColors = String(uniqueColors.size);
}
This is the implementation from the other site:
function countPixels(data) {
const colorCounts = {};
for(let index = 0; index < data.length; index += 4) {
const rgba = `rgba(${data[index]}, ${data[index + 1]}, ${data[index + 2]}, ${(data[index + 3] / 255)})`;
if (rgba in colorCounts) {
colorCounts[rgba] += 1;
} else {
colorCounts[rgba] = 1;
}
}
return colorCounts;
}
As you can see, besides the implementations being similar, they output very different results - my site says I have 256 unique colors, while the other says there's only two. I also tried to just copy and paste the implementation but I got the same 256. That's why I imagine the problem is in my canvas, but I can't figure out what's going on.
You are scaling your image, and since you didn't tell which interpolation algorithm to use, a default smoothing one is being used.
This will make all the pixels that were on fixed boundaries and should now span on multiple pixels to be "mixed" with their white neighbors and produce shades of gray.
There is an imageSmoothingEnabled property that tells the browser to use a closest-neighbor algorithm, which will improve the situation, but even then you may not have a perfect result:
const canvas = document.querySelector("canvas");
const width = canvas.width = innerWidth;
const height = canvas.height = innerHeight;
const ctx = canvas.getContext("2d");
const img = new Image();
img.crossOrigin = "anonymous";
img.src = "https://raw.githubusercontent.com/ajsaraujo/unique-color-count-mre/master/src/assets/image.png";
img.decode().then(() => {
ctx.imageSmoothingEnabled = false;
ctx.drawImage(img, 0, 0, width, height);
const data = ctx.getImageData(0, 0, width, height).data;
const pixels = new Set(new Uint32Array(data.buffer));
console.log(pixels.size);
});
<canvas></canvas>
So the best would be to not scale your image, or to do so in a computer friendly fashion (using a factor that is a multiple of 2).
Is there any method to replace/remove colors by color range in Javascript, Opencv or anything else that can be operated on website?
As the above image. Is that possible to replace all the white color(It can be white or near white colors) with transparent color? Any suggestion would be appreciated.
With imagemagick this can be done quickly.
convert input.jpg -fuzz 6% -transparent white output.png
The value of -fuzz 6% can be adjusted to match "near white" thresholds.
Note: The format of JPEG has changed to PNG; which, supports transparency.
You could create a canvas and draw that image onto it, that way you're able to get pixel colors and manipulate them. (And also save the result)
This might lead you somewhere to start with. If you require further help, just comment.
EDIT: Little sample of what this should work like:
//Sets up canvas containing the image:
var img = document.getElementById("image");
img.crossOrigin = "Anonymous";
img.src = "https://i.imgur.com/X1fKQsK.jpg";
loadedBefore = false;
img.onload = function(){
if(loadedBefore) return;
else loadedBefore = true;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,img.width,img.height);
//Finds pixels matching color black:
for(x=0; x<canvas.width; x++){
for(y=0; y<canvas.height; y++){
imgdata = ctx.getImageData(x,y,1,1);
color = imgdata.data; //Gets color of coordinate (with 1 pixel in size)
if(color[0] > 250 && color[1] > 250 && color[2] > 250){ //Checks if color is pretty white
color[3] = 0; //Sets alpha to 0 -> Makes color transparent
ctx.putImageData(imgdata,x,y);
}
}
}
img.src = canvas.toDataURL(); //Set image to display canvas content / update image
console.log("done!");
}
<img id="image"/>
You can apparently not just load an image from some other website and modifiy it in the canvas, unless you set img.crossOrigin = "Anonymous" and the other website allows it. I got no clue on what exactly happens there, I just know that it works with imgur.com. (That's why everything's in the onload function now)
The loadedBefore stuff is because StackOverflow apparently calls the img.onload function pretty often, you won't have this issue if you use your own image so you don't need the crossOrigin and onload stuff.....
Just a function to do the stuff:
function whiteToTransparent(img){
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,img.width,img.height);
//Finds pixels matching color black:
for(x=0; x<canvas.width; x++){
for(y=0; y<canvas.height; y++){
imgdata = ctx.getImageData(x,y,1,1);
color = imgdata.data;
if(color[0] > 250 && color[1] > 250 && color[2] > 250){
color[3] = 0;
ctx.putImageData(imgdata,x,y);
}
}
}
img.src = canvas.toDataURL();
}
Can someone help me to fix the issue?
I want to apply alpha layer mask to make some of the image transparent using canvas.
Thanks a lot.
var redImageData = redCanvas.getContext("2d").getImageData(0, 0, 200, 200); //overlay
var ImageData = imageCanvas.getContext("2d").getImageData(0, 0, 200, 200);
var px = redImageData.data;
var px2 = ImageData.data;
for(var i = 0; i < px.length; i += 4) {
if(px[i + 0] == 0 && px[i + 1] == 0 && px[i+2] == 0){
px[i + 3] = 0;
} else {
px[i + 0] = px2[i + 0];
px[i + 1] = px2[i + 1];
px[i + 2] = px2[i + 2];
px[i + 3] = px2[i + 3];
}
}
ctx.imageSmoothingEnabled = true;
ctx.putImageData(redImageData, 0, 0);
alpha mask overly https://i.stack.imgur.com/zCzOf.png
The linked image is not really an alpha mask but a matte image. The difference is that a matte image represent what would be an alpha-channel but showing it as RGB (or gray-scale) components. It doesn't actually have an alpha-channel. Matte images are common in video-compositing software but not so useful on web.
Canvas, or the Porter-Duff methods it uses, does not support matte images directly so they have to first be converted to an actual alpha-channel. To do this you have to iterate over each pixel and move one of the component values (from red, green or blue - doesn't matter which) into the alpha-channel.
When that is done you can use the canvas object that now has proper alpha-channel with composite operations which only uses the alpha information (blending modes is a different chapter).
The better approach is of course to provide the images as PNG with a proper alpha channel. But in any case, to show it's possible to also work with matte images, although not as efficient, we can do the following:
Converting matte image into alpha channel
First step: this code section shows how you can efficiently do the pre-step of converting the matte image into an alpha channel. The resulting colors are not important for the main compositing step as it will only use the alpha-channel, as already mentioned.
Just make sure the image has loaded properly before trying to use the image by either using the image's onload callback or running the script after everything has loaded.
This code will simply shift a component (blue in this case) using the full 32-bit value of the pixel (for efficiency) into the alpha-channel which leaves the image looking cyan but with proper alpha as you can see with the orange background showing through (most of the code is to handle loading and setup though).
window.onload = function() {
// at this stage the image has loaded:
var img = document.getElementById("img");
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
// - setup canvas to match image
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
// - draw image
ctx.drawImage(img, 0, 0);
// CONV. STEP: move a component channel to alpha-channel
var idata = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data32 = new Uint32Array(idata.data.buffer);
var i = 0, len = data32.length;
while(i < len) {
data32[i] = data32[i++] << 8; // shift blue channel into alpha (little-endian)
}
// update canvas
ctx.putImageData(idata, 0, 0);
};
body {background: #f72; font-size:44px; color:rgba(0,0,0,0.5)}
<img id="img" crossorigin="anonymous" src="https://i.imgur.com/QRGYuWg.png"> ►
<canvas id="c"></canvas>
Compositing
The second part then becomes about compositing using the new alpha-channel.
In this case the matte image's black becomes fully transparent while the white becomes fully opaque. You could have reversed this in the conversion step but it does not really matte as long as you're aware of the how the matte image looks.
To replace the interior content we use compositing mode source-in. This will replace the content depending on the alpha value while keeping the alpha-channel as it is.
Dealing with the interior part first using the same mode allows us to do additional things with the content before drawing the frame (think vignette, shadows etc.).
As the final step we fill in the transparent areas, the frame itself, by using the composite mode destination-over which replaces the more transparent ares with the content being drawn to canvas (conceptually it draws "behind" the existing content).
The code below uses simple colored boxes - just replace those with whatever you want to draw.
window.onload = function() {
var img = document.getElementById("img");
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
var idata = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data32 = new Uint32Array(idata.data.buffer);
var i = 0, len = data32.length;
while(i < len) data32[i] = data32[i++] << 8;
ctx.putImageData(idata, 0, 0);
// COMP. STEPS: use the mask with composite operation. Since our frame
// is black (= transparent as alpha) we can use the following mode:
ctx.globalCompositeOperation = "source-in";
// draw something, here a blue box, replace with whatever you want
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// to fill the frame area, still transparent, use this mode:
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "yellow";
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
body {background: #f72; font-size:44px; color:rgba(0,0,0,0.5)}
<img id="img" crossorigin="anonymous" src="https://i.imgur.com/QRGYuWg.png"> ►
<canvas id="c"></canvas>
I have a large amount of images with a black background, here is one for example:
Is it possible through Javascript to have to ignore the black (#000000) and have it draw on canvas? to appear like this?
Basically trying to take the black pixels and make it an alpha channel.
So you'll need to run through all the pixels and change the alpha value of all the black pixels.
https://jsfiddle.net/0kuph15a/2/
This code creates a buffer (empty canvas) to draw the original image to. Once thats done, it takes all the pixels of this buffer canvas and then iterates over all the pixels and checks their values. I add up the Red, Blue, and Green values to see if they are less then 10 (just incase some pixels aren't pure black 0), but would visually appear black to the human eye. If it is less then 10 it simply turns the alpha value of that pixel to 0.
var canvas = document.getElementById('main');
var ctx = document.getElementById('main').getContext('2d');
var tile = new Image();
tile.src = document.getElementById('image').src;
tile.onload = function() {
draw(tile);
}
function draw(img) {
var buffer = document.createElement('canvas');
var bufferctx = buffer.getContext('2d');
bufferctx.drawImage(img, 0, 0);
var imageData = bufferctx.getImageData(0,0,buffer.width, buffer.height);
var data = imageData.data;
var removeBlack = function() {
for (var i = 0; i < data.length; i += 4) {
if(data[i]+ data[i + 1] + data[i + 2] < 10){
data[i + 3] = 0; // alpha
}
}
ctx.putImageData(imageData, 0, 0);
};
removeBlack();
}
You can easily change this line if(data[i]+ data[i + 1] + data[i + 2] < 10){ to if(data[i]+ data[i+1] + data[i+2]==0){ if you know for a fact only #000 blacks are used.
You can accomplish that using blend modes.
Change the context globalCompositeOperation to screen, and you can get that result. Here's an example:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = new Image();
image.src = "https://images.blogthings.com/thecolorfulpatterntest/pattern-4.png";
image.onload = function() {
context.drawImage(image, 0, 0, canvas.width, canvas.height);
var blackImage = new Image();
blackImage.src="http://www.printmag.com/wp-content/uploads/Sillitoe-black-white.gif";
blackImage.onload = function(){
context.globalCompositeOperation = "screen";
context.drawImage(blackImage, 0, 0, canvas.width, canvas.height);
}
};
<canvas id="canvas" width="300" height="250"></canvas>
<hr/>
<h1>Images used:</h1>
<img src="https://images.blogthings.com/thecolorfulpatterntest/pattern-4.png"/>
<img src="http://www.printmag.com/wp-content/uploads/Sillitoe-black-white.gif"/>
How about saving the picture as an .svg file...from there you can change all colors and other settings
Felipe's answer addressed my issue. Alpha pixel manipulation does not work
(eg, setting every 4th pixel to 0) for preserving alphatransparency with multiple images added into the same context at the same time.
eg:
this.ctx1.putImageData(output, 0, 0); // without setting the context's globalCompositeOperation, this image is written over by the next putImage operation
this.ctx1.putImageData(output, 20, 0);
Go here to review the blending options. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
Okay, I am confused with get Image Data function for
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData
I have a path image that is in png format with transparent background above. What I need to get are the coordinates x,y for both left and right edges of the path at height/2. (The points of the red arrows)
Is getImageData the right function to use? Can anyone give some advice on how to get them?
Thanks in advance.
Yes, use getImageData(x, y, width, height);
In the case you have only two colors (here transparent & white) :
var img = new Image();
img.onload = getPoints;
img.crossOrigin = 'anonymous';
img.src = "https://dl.dropboxusercontent.com/s/lvgvekzkyqkypos/path.png";
function getPoints(){
// set our canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
// draw the image
ctx.drawImage(this,0,0);
// get the middle y line
var imageData = ctx.getImageData(0,Math.floor(this.height/2), this.width, 1);
var data = imageData.data;
// set an empty object that will store our points
var pts = {x1: null, y1: Math.floor(this.height/2), x2: null, y2:Math.floor(this.height/2)};
// define the first opacity value
var color = 0;
// iterate through the dataArray
for(var i=0; i<data.length; i+=4){
// since we'relooking only for non-transparent pixels, we can check only for the 4th value of each pixel
if(data[i+3]!==color){
// set our value to this new one
color = data[i+3];
if(!pts.x1)
pts.x1 = i/4;
else
pts.x2 = i/4;
}
}
snippet.log('start points : '+pts.x1+'|'+pts.y1);
snippet.log('end points : '+pts.x2+'|'+pts.y2);
ctx.fillStyle = 'red';
ctx.fillRect(pts.x1-5, pts.y1, 10, 10);
ctx.fillRect(pts.x2-5, pts.y2, 10, 10);
document.body.appendChild(canvas);
}
body{background-color: blue}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>