【发布时间】:2021-12-30 01:44:43
【问题描述】:
我想检测图像或“绘制”区域的角点(左上角和右下角)。为此,我想使用 javascript 库 p5.js。 findTop() 和 findBottom() 这两个函数应该可以识别角点。
起点是一只猫的草图(图 1)。最后要识别图纸的两个角点(见图 2)。
过程如下: 用两个 For 循环遍历图像数组(这里是像素 [])。对于每个像素,应检查内容是否为黑色,如果是,则比较其是否为最小的 x 和 y 值 (x1|y1)。为了控制,相应的像素对是粉红色的。第二个 findBottom() 函数的工作方式类似。不幸的是我无法找到正确的坐标,但我不知道我做错了什么......
任何帮助将不胜感激:-)
let img;
let x1, y1;
let x2, y2;
let wid = 720;
let hei = 400;
function setup() {
createCanvas(wid, hei);
img = loadImage('cat.jpg');
pixelDensity(1);
}
function draw() {
image(img, 0, 0);
loadPixels();
findTop();
findBottom();
ColorizePixel(x1,y1);
ColorizePixel(x2,y2);
updatePixels();
}
function findTop() {
x1=wid;
y1=hei;
for(let y=0; y<width; y++) {
for(let x=0; x<height; x++) {
let index = (x + y * width) * 4;
if(pixels[index] < 255 && x < x1){
x1 = x;
}
if(pixels[index] < 255 && y < y1){
y1 = y;
}
}
}
}
function findBottom() {
x2=0;
y2=0;
for(let y=0; y<width; y++) {
for(let x=0; x<height; x++) {
let index = (x + y * width) * 4;
if(pixels[index] < 255 && x > x2){
x2 = x;
}
if(pixels[index] < 255 && y > y2){
y2 = y;
}
}
}
}
function ColorizePixel(x,y){
let chosenPixel = (y * width + x) * 4;
pixels[chosenPixel]=255;
pixels[chosenPixel+1]=0;
pixels[chosenPixel+2]=255;
pixels[chosenPixel+3]=255;
}
编辑#2
let img;
let x1, y1,x2, y2;
let newImage;
let wid = 720;
let hei = 400;
function setup() {
createCanvas(wid, hei);
img = loadImage('cat.jpg'); // Load the image
pixelDensity(1);
}
function draw() {
image(img, 0, 0);
loadPixels();
findTop();
findBottom();
ColorizePixel(x1,y1);
ColorizePixel(x2 ,y2);
updatePixels();
}
function findTop() {
x1=720;
y1=400;
for(let y=0; y<height; y++) {
for(let x=0; x<width; x++) {
let index = (x + y * width) * 4;
if(pixels[index] < 122 && x < x1){
x1 = x;
}
if(pixels[index] < 122 && y < y1){
y1 = y;
}
}
}
}
function findBottom() {
x2=0;
y2=0;
for(let y=0; y<height; y++) {
for(let x=0; x<width; x++) {
let index = (x + y * width) * 4;
if(pixels[index] < 122 && x > x2){
x2 = x;
}
if(pixels[index] < 122 && y > y2){
y2 = y;
}
}
}
}
//Farebe Pixel Pink ein
function ColorizePixel(x,y){
let chosenPixel = (y * width + x) * 4;
pixels[chosenPixel]=255;
pixels[chosenPixel+1]=0;
pixels[chosenPixel+2]=255;
pixels[chosenPixel+3]=255;
}
【问题讨论】:
-
感谢您的回答。我在代码下方添加了结果图片。我上面左点的 X 坐标 (x1) 显示正确。不幸的是,Y 坐标 (y1) 的值是 0。对于 findBottom() 方法,值是 x2=399 和 y2=311。
标签: javascript image-processing processing p5.js