我正在为相框实现接缝雕刻算法。
https://en.wikipedia.org/wiki/Seam_carving
我知道这个算法不是很好,因为它从图片中切出一条直缝,但好消息是我这样做是为了“相框”,所以你可以想象它会工作得很好。
因此,如果图像宽度为 100 像素,我想删除第 50 像素处的垂直线。那么宽度将为 99 像素。
这是伪代码,我删除了之前的代码尝试
- 将图像加载到 Canvas 上。
- 删除一条宽度为 1 像素、高度等于加载图像的垂直线。如果该图像的宽度等于 100,则现在为 99。
- 获取新处理图像的 Base64 编码字符串。
我想要做的是删除一条宽度为1像素且高度等于图像的垂直线,然后将图像绘制到 Canvas 上并获得base64编码的图像。
最佳答案
您可以使用原始图像作为源,然后将 Canvas 设置为最终尺寸,例如:
var img=new Image; img.onload=carve; img.src = "//i.stack.imgur.com/OqB5r.jpg";
function carve() {
var ctx = c.getContext("2d");
var cut = 50; // we remove [50, 50 + carveWidth>, in this case
var carveWidth = 16; // exaggerated to show noticeable change
// set final size of canvas:
c.width = this.width - carveWidth;
c.height = this.height;
// draw in first half using clip arguments of drawImage()
ctx.drawImage(this, 0, 0, cut, this.height, 0, 0, cut, this.height);
// draw in second half, notice we skip cut+carve for source, but not for dest.
ctx.drawImage(this, cut + carveWidth, 0, this.width, this.height,
cut , 0, this.width, this.height);
// save out canvas
}
canvas {border:1px solid red} /* to show actual canvas size */
<canvas id=c></canvas>
对于算法,您需要执行类似的操作,但使用雕刻路径作为前半部分的掩码:
- 以目标尺寸绘制图像(完整)
- 使用复合模式通过封闭路径剪掉后半部分来消除不规则的声音
- 使用复合模式destination-over
- 在图像中绘制减去接缝的偏移量 - 这将在前半部分后面绘制,从而形成完整的图像
对每个接缝重复此操作。
关于javascript - html5 canvas删除垂直/水平线像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258781/