当我接手这个项目时,我认为像黑白/棕褐色这样的滤镜很难通过照片处理来制作。一切都变得更简单!
下面我将给出一个有趣的算法,用于将图像分解为像素光谱并处理照片。
<h1>filter fun</h1> <script src="https://www.dukelearntoprogram.com/course1/common/js/image/simpleimage.js"> </script> <canvas id="can"></canvas> <p> <b> load image: <input type="file" multiple="false" accept="image/*" id="file" onchange="loadimage()"> </b> </p> <input type="button" id="button" value="grayscale" onclick="dogray()"> <input type="button" id="button" value="red" onclick="dored()"> <input type="button" id="button" value="rainbow" onclick="dorainbow()"> <p> <input type="button" id="button" value="reset image" onclick="reset()"> </p>
我暗示类似这样的事情(当然,任何文件):
即使是最简单的设计,最好还是对齐。您将更快地掌握大型项目的窍门。
h1 { font-size: 22pt; font-family: arial; color: #008b8b; } body { background-color: #f5f5dc; } p { font-size: 16pt; } canvas { width: 400px; background-color: #add8e6; border: 2px solid #a9a9a9; } input { font-size: 12pt; }
算法的本质如下:
- 互联网上的任何图像都会分解为光谱:红、绿、蓝
- 创建3个数组,存储图像中对应颜色的像素个数(详细函数见代码)
- 选择滤镜时:依次处理3个数组以增加/减少调色板值
var imgFile; var image = null; var imageGray = null; var imageRed = null; var imageRainbow = null; var canvas = null; function loadImage(){ canvas = document.getElementById("can"); imgFile = document.getElementById("file"); image = new SimpleImage(imgFile); imageGray = new SimpleImage(imgFile); imageRed = new SimpleImage(imgFile); imageRainbow = new SimpleImage(imgFile); image.drawTo(canvas); } function imageIsLoaded(img) { if (img==null || !img.complete()) { alert("Image not loaded"); return false; } else { return true; } } function doGray(){ if (imageIsLoaded(image)) { for (var pixel of imageGray.values()) { var arg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue())/3; pixel.setRed(arg); pixel.setGreen(arg); pixel.setBlue(arg); } imageGray.drawTo(canvas); } } function doRed(){ if (imageIsLoaded(image)) { for (var pixel of imageRed.values()) { var arg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue())/3; if (arg < 128) { pixel.setRed(arg*2); pixel.setGreen(0); pixel.setBlue(0); } else { pixel.setRed(255); pixel.setGreen(arg*2-255); pixel.setBlue(arg*2-255); } } imageRed.drawTo(canvas); } } function doRainbow(){ if (imageIsLoaded(image)) { imageRainbow.drawTo(canvas); } } function Reset(){ image = new SimpleImage(imgFile); imageGray = new SimpleImage(imgFile); imageRed = new SimpleImage(imgFile); imageRainbow = new SimpleImage(imgFile); image.drawTo(canvas); }
这似乎是一个简单的算法,但它有助于理解图像像素并根据调色板进行处理。我认为它值得你关注!