在p5中调整画布的大小,但不清除内容,而是将其映射为新的大小

问题描述 投票:0回答:1

访问此链接以在p5 Web编辑器here中运行代码

function setup() {
  createCanvas(280, 280);
  background(0);
}

function draw() {
  strokeWeight(25);
  if (mouseIsPressed) {
    stroke(255);
    line(mouseX, mouseY, pmouseX, pmouseY);
  }
}


function predict() {
  resizeCanvas(28, 28);
}

[尝试实现一个数字分类器,用户将在该数字分类器上绘制数字,然后对神经网络进行分类,但是当神经网络训练了该维度的MNIST数据集的图像时,该神经网络期望的是28x28的图像,但问题是画布是否要小用户将无法绘制任何内容,因此我想要的是将画布的尺寸调整为28x28尺寸,然后加载画布的pixels并执行剩余的过程。但是当我这样做时,画布被清除了,所以关于如何不丢失图形而是将其映射到新尺寸的任何建议。


或者也许这不是首先调整画布大小并加载像素的好方法因此,欢迎您提出任何其他建议。.感谢您的帮助。

javascript machine-learning processing p5.js
1个回答
1
投票

您可以在另一个具有所需尺寸的图形对象中绘制主画布的内容,然后操纵其像素数组:

let cnv
function setup() {
  cnv = createCanvas(280, 280);
  background(0);
}

function draw() {
  strokeWeight(25);
  if (mouseIsPressed) {
    stroke(255);
    line(mouseX, mouseY, pmouseX, pmouseY);
  }
}

function predict() {
  //Auxiliar graphics object
  let resized = createGraphics(28, 28)

  //Draw and scale the canvas content
  resized.image(cnv, 0, 0, 28, 28)
  
  //Manipulate the new pixels array
  resized.loadPixels()
  console.log(resized.pixels)

  // Draw the 28x28 just for visual feedback
  image(resized, 0, 0) 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

<button onClick="predict()">PREDICT</button>
© www.soinside.com 2019 - 2024. All rights reserved.