我想檢測影像或“繪制”區域的角點(左上角和右下角)。為此,我想使用 javascript 庫 p5.js。兩個函式 findTop() 和 findBottom() 應該識別角點。
起點是貓的草圖(圖 1)。最后應識別出圖紙的兩個角點(見圖 2)。
圖 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;
}
運行該代碼的結果 #2
uj5u.com熱心網友回復:
在繪制影像和檢測角之前,您需要用白色不透明顏色填充背景:
function draw() {
background(255, 255, 255);
image(img, 0, 0);
// [...]
}
uj5u.com熱心網友回復:
我看到兩個問題。
回圈
您的回圈將 y 運行到寬度而不是高度,將 x 運行到高度而不是寬度。我之前沒有發現。
JPEG格式
您正在處理 JPEG 檔案。這意味著有損壓縮。
平坦的顏色不會保持平坦。
不要指望白色正好是255。
選擇一個不太嚴格的閾值,否則您可能會“捕獲”整個 jpeg 塊,而不僅僅是非白色像素,因為如果壓縮足夠嚴重,包含一些不同像素的塊將導致所有像素失真。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401051.html
標籤:javascript 图像处理 加工 p5.js
上一篇:如何從Prometheus服務器獲取按特定標簽過濾的所有指標名稱
下一篇:ImageDataGenerator(Keras)中的channel_shift_range和brightness_range的區別?
