从位图分配 Renderscript

Renderscript allocation from bitmap

我正在尝试进入渲染脚本并且对分配使用感到困惑。几乎所有示例都显示下一个算法:

  1. 创建进出位图
  2. 从位图 In 和 Out 相应地创建 In 和 Out 分配
  3. 配置脚本并执行forEach方法
  4. 使用 copyTo 方法将 Out 分配的结果复制到位图中

类似的东西:

    Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena);
    Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());

    Allocation allocationIn = Allocation.createFromBitmap(renderScript, srcBitmap);
    Allocation allocationOut = Allocation.createFromBitmap(renderScript, dstBitmap);

    scriptColorMatrix.setGreyscale();

    scriptColorMatrix.forEach(allocationIn, allocationOut);

    //no difference after removing this line
    allocationOut.copyTo(dstBitmap);

    imagePreview.setImageBitmap(dstBitmap);

这有效,但即使我通过删除省略了第 4 步,它也有效:

allocationOut.copyTo(dstBitmap);

让我们走得更远,降低灰度后的亮度:

    Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena);
    Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());

    Allocation allocationIn = Allocation.createFromBitmap(renderScript, srcBitmap);
    Allocation allocationOut = Allocation.createFromBitmap(renderScript, dstBitmap);

    scriptColorMatrix.setGreyscale();

    scriptColorMatrix.forEach(allocationIn, allocationOut);

    //reset color matrix
    scriptColorMatrix.setColorMatrix(new Matrix4f());

    //adjust brightness
    scriptColorMatrix.setAdd(-0.5f, -0.5f, -0.5f, 0f);

    //Performing forEach vise versa (from out to in)
    scriptColorMatrix.forEach(allocationOut, allocationIn);

    imagePreview.setImageBitmap(srcBitmap);

简单描述一下上面的代码,我们将灰度颜色矩阵从In分配到Out一个,并向后调整亮度。我从来没有调用过 copyTo 方法,但最后我在 srcBitmap 中得到了结果,它是正确的。

这还没有结束。让我们更深入一点。我将只留下一张位图和一个分配:

    Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena);

    Allocation allocationIn = Allocation.createFromBitmap(renderScript, srcBitmap);

    scriptColorMatrix.setGreyscale();

    scriptColorMatrix.forEach(allocationIn, allocationIn);

    //reset color matrix
    scriptColorMatrix.setColorMatrix(new Matrix4f());

    //adjust brightness
    scriptColorMatrix.setAdd(-0.5f, -0.5f, -0.5f, 0f);

    scriptColorMatrix.forEach(allocationIn, allocationIn);

    imagePreview.setImageBitmap(srcBitmap);

结果是一样的...



谁能解释为什么会发生这种情况以及在哪里使用 copyTo 以及在没有它的情况下我可以在哪里使用定位位图?

需要 Allocation 对象才能将 Bitmap 正确映射到 Renderscript 可以理解的内容。如果您的目标是 API 18 或更高版本,您使用的 Allocation.createFromBitmap() 方法会自动给出标志 USAGE_SHARED,它试图让 Allocation 使用相同的后备内存作为 Bitmap 对象。所以这两个是 linked 但技术上仍然需要 copyTo() 方法,因为 RS 实现可能需要将其同步回来。在某些平台上,这可能已经发生,而其他平台可能会导致此暂停,因为 DMA 或其他机制正在使用 RS 代码所做的任何更改更新 Bitmap 的后备内存。

至于为什么您可以在调用脚本时颠倒 in/out Allocation 顺序 - 这是有效的,您可以自行决定参数和顺序是否正确。对于 RS,它们只是指向某种类型的待操作支持数据的对象。由于两者都是使用 Allocation.createFromBitmap() 调用创建的,因此只要 Bitmap 对象是可变的,它们就可以用作输入或输出。

同理,输入输出使用相同的Allocation也不正常,但也不无效。这只是意味着您的输入正在动态变化。只要您的脚本在为特定 Element 调用根函数时不访问数据中的其他 Element,那么它应该可以工作(如您所见。)